2011-05-28 162 views
2

此代码应该创建一个字符串数组,然后将它们随机排序,然后打印订单。不幸的是,它在其中一个空格中添加了空行(我认为这是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; 
} 
+1

你不需要编写自己的'swap()',在STL中有一个['swap()'](http://www.cplusplus.com/reference/algorithm/swap/)。 – Johnsyweb 2011-05-28 09:49:13

回答

6

getline()第一个电话会立即打到用户输入size后进入了换行,因此将返回一个空字符串。在第一次致电getline()之前尝试致电cin.ignore(255, '\n');。这将跳过255(任意选择的字符)字符,直到遇到\n(并且换行符也将被跳过)。

编辑:由于@Johnsyweb和@ildjarn指出,std::numeric_limits<streamsize>::max()是一个比255更好的选择。

+2

不太随意:'std :: cin.ignore(std :: numeric_limits :: max(),'\ n');' – Johnsyweb 2011-05-28 02:48:17

+1

+1用于减少随意性,-epsilon用于增加详细度;-) – 2011-05-28 02:50:21

+1

它不会减少任意性,这是零任意性。也就是_correct_。 – ildjarn 2011-05-28 06:34:18