如何解决一次的字符串排序数组
| 该代码应该构成一个字符串数组,对它们进行随机排序,然后打印该顺序。不幸的是,它在其中一个空格中添加了一个空白行(我认为这是getline的工作)。任何想法如何解决?我尝试设置数组[0] = NULL;它抱怨运营商...#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <string>
#include <cstdlib>
using std::cout;
using std::endl;
using namespace std;
void swap (string &one,string &two)
{
string tmp = one;
one = two;
two = tmp;
}
int rand_loc (int size)
{
return (rand() % size);
}
int main()
{
srand(time(NULL));
int size;
cin >> size;
string *array = new string[size];
//array[0] = NULL ;
for (int x = 0; x < size; x++)
{
getline(cin,array[x]);
}
//for (int x = 0; x < size; x++)
//{
// swap (array[rand_loc(size)],array[rand_loc(size)]);
//}
cout << endl;
for (int x = 0; x < size; x++)
{
//out << array[x] << endl;
int y = x + 1;
cout<<y<<\".\"<<\" \"<<array[x]<<endl;
}
delete[] array;
}
解决方法
第一次调用
getline()
将立即打入用户在输入size
之后输入的换行符,因此将返回一个空字符串。尝试在第一次呼叫ѭ1之前先呼叫cin.ignore(255,\'\\n\');
。这将最多跳过255个(任意选择的数字)字符,直到遇到ѭ5(并且换行符也将被跳过)。
编辑:正如@Johnsyweb和@ildjarn指出的那样,std::numeric_limits<streamsize>::max()
比than7ѭ要好得多。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。