2010-03-20 44 views
1

我有以下方法,它不會捕捉用戶的任何內容。如果我爲藝術家名稱輸入新樂隊,它只捕捉「新」並將樂隊輸出「樂隊」。如果我使用cin.getline()而不捕獲任何內容。任何想法如何解決這一問題?C++ cin問題。不捕捉用戶的輸入

char* artist = new char [256]; 

char * getArtist() 
{ 
    cout << "Enter Artist of CD: " << endl; 
    cin >> artist;  
    cin.ignore(1000, '\n'); 
    cout << "artist is " << artist << endl; 
    return artist; 
} 

這工作得很好。謝謝你羅傑

std::string getArtist() 

{ 

    cout << "Enter Artist of CD: " << endl; 

    while(true){    

     if (getline(cin, artist)){ 

     } 

    cout << "artist is " << artist << '\n'; 

    } 

    return artist; 

} 
+3

請使用'std :: string'並且不要使用'new []'。 – avakar

回答

2
std::string getArtist() { 
    using namespace std; 
    while (true) { 
    cout << "Enter Artist of CD: " << endl; 
    string artist; 
    if (getline(cin, artist)) {    // <-- pay attention to this line 
     if (artist.empty()) { // if desired 
     cout << "try again\n"; 
     continue; 
     } 
     cout << "artist is " << artist << '\n'; 
     return artist; 
    } 
    else if (cin.eof()) { // failed due to eof 
     // notice this is checked only *after* the 
     // stream is (in the above if condition) 

     // handle error, probably throw exception 
     throw runtime_error("unexpected input error"); 
    } 
    } 
} 

整個事情是一個普遍改善,但使用函數getline的可能是你的問題最爲顯著。

void example_use() { 
    std::string artist = getArtist(); 
    //... 

    // it's really that simple: no allocations to worry about, etc. 
} 
+0

這工作正常,除了每次我得到「再試一次」。任何想法如何解決這個問題? – user69514

+0

@user:如上所述,只有當輸入爲空(用戶按下提示輸入而不輸入任何內容)時纔會發生這種情況。也許你誤了它? – 2010-03-20 23:34:40

1

這是指定的行爲; istream只能讀取空格或換行符。如果您需要整行,則可以使用getline方法,正如您已經發現的那樣。

另外,請在任何新的C++代碼中使用std::string而不是char*,除非有非常好的理由。在這種情況下,它可以幫助您避免緩衝區溢出等各種問題,而無需您付出額外的努力。

0

如果您要在輸入中使用空格分隔符,則需要使用getline作爲輸入。這會讓你忽略不必要的。