这段代码应该创建一个字符串数组,对它们进行随机排序,然后打印顺序。不幸的是,它在其中一个空格中添加了一个空行(我认为这是 getline 所做的)。有什么想法如何解决这个问题吗?我尝试设置 array [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
后会立即命中用户输入的换行符,因此将返回一个空字符串。尝试调用cin.ignore(255, '\n');
在第一次调用 getline()
之前。这将跳过最多 255 个(任意选择的数字)字符,直到 \n
遇到(并且换行符也将被跳过)。
编辑:正如@Johnsyweb 和@ildjarn 指出的那样,std::numeric_limits<streamsize>::max()
是一个比 255
更好的选择.
关于c++ - 一次性对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6159275/