2011-05-28 103 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