2011-10-16 30 views
1

獲得答案我是一名初級程序員,可能是您的計算機專家可能弄錯的錯誤代碼。我已經記住了一個段落程序供我自己使用,你能想出一個辦法,以便每次都會發生getline嗎?這裏是我的代碼...我該如何讓.getline每次都能通過

#include <iostream> 
#include <string> 
#include <Windows.h> 

using namespace std; 

void main(){ 
    string sentence; 
    string attempt; 
    char key; 
    int counter = 0; 

    cout << "Insert your sentence/paragraph (will be case sensitive) (don't press  enter until you're done)." << endl << endl; 
    getline (cin, sentence); 
    cout << endl; 
    while (true){ 
     system ("cls"); 
     Sleep (5); 
     cout << "Now enter the sentence/paragraph" << endl; 
      getline (cin, attempt); 
     if (sentence == attempt){ 
      cout << "Good job, do you want to go again? N for no, anything else for  yes" << endl; 
      cin >> key; 
      if (key == 'n' || key == 'N'){ 
       break; 
      } 
     } 
     else{ 
      cout << "You messed up, try again." << endl; 
      system("pause"); 
      continue; 
     } 
    } 
    system("pause"); 

}

+0

[C++ getline()的可能重複不等待多次調用時從控制檯輸入](http://stackoverflow.com/questions/7786994/c-getline-isnt-waiting-for-input-from -console - 當所謂的海報倍) – ildjarn

回答

0

沒有通過您的代碼將所有的方式。調用getline()後,字節很可能會留在輸入緩衝區中。我會用ASCII藝術來解釋。

說你的緩衝區看起來像這樣,每個空白框可以容納一個字節。

|_|_|_|_|_|...|_|

當你輸入一個詞組(如 「FOO」),然後按Enter鍵,緩衝看起來是這樣的:

|F|O|O|\n|_||_|...|_|

'\n'字符(換行符)添加按Enter鍵。

getline()讀取緩衝區時,它會讀取直到它遇到換行符,但它不會將其刪除。因此,調用如下:

getline(cin, str) // = "FOO" 
|\n|_|_|...|_| // buffer after call 

getline()下一次調用將在新行讀取(並且被從緩衝區中取出)。

getline(cin, str) // = "\n" 
|_|_|_|_|_|...|_| // buffer after call 

此行爲導致從輸入緩衝區中讀取「清除緩衝區」的常見做法。這可以通過做

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

每個緩衝區讀取後。它也有助於將其定義爲宏或內聯函數,以便隨時快速調用它。

相關問題