这段代码应该是一个字符串数组,随机排序,然后打印顺序.不幸的是,它在其中一个空格中添加了一个空行(我认为这是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;
}
Run Code Online (Sandbox Code Playgroud)
第一次调用getline()将立即触及用户在输入后输入的换行符,size因此将返回一个空字符串.尝试cin.ignore(255, '\n');在第一次通话前拨打电话getline().这将跳过最多255个(任意选择的数字)字符,直到\n遇到a(并且也会跳过换行符).
编辑:正如@Johnsyweb和@ildjarn指出的那样,std::numeric_limits<streamsize>::max()是一个更好的选择255.