2015-10-15 40 views
2

編輯getline()可以跳過不帶用戶輸入嗎?

的問題是,我是在我的程序的另一點使用cin >>,因此出現了在流緩存一個換行符。


所以主要的問題是關於getline(),但爲了把它放到透視中,你必須先看到我的代碼。出於某種奇怪的原因,當我運行我的程序時,它首次在整個循環中運行得非常好。但第二次它跳過了我的getline(cin, inputMenu)陳述。是的,我知道這是一個非常基本的程序,我知道沒有其他錯誤,因爲我已經從字面上測試了它的所有其他方面。有沒有我不知道的getline()

while (1) 
    { 
     // Reset the input each loop 
     inputMenu = "ABC"; 

     // Menu 
     cout << "Menu\n P (Purchase)\n S (Shut down)" << "\n\n You decide: "; 

     /* I put this if statement as a test, to make sure that it always runs getline. 
     But for some odd reason when I run it I get this (see run below)*/ 
     if(1) 
     getline(cin, inputMenu); 

     //Blah blah all the other stuff if they enter a P or S. (Not an infinite loop) 

     cout << "\nYou just earned " << inputYogurt << " stamps!" 
      << " Bringing your grand total to " << numStamps << "!\n" << endl; 
     } 
    } 


---------------------- Run -------------------- 
Menu 
    P (Purchase) 
    S (Shut down) 

    You decide: p 

How many yogurts would you like to buy? 3 

You just earned 3 stamps! Bringing your grand total to 3! 


Menu 
    P (Purchase) 
    S (Shut down) 

    You decide: Menu  <<<<<<<<<<<<<<<<<<<<<<<<<< Thats my error 
    P (Purchase) 
    S (Shut down) 

    You decide: 

------------------------------------------------------- 

它跳過getline()語句,只是再次運行循環。也許我不太瞭解getline(),因爲很明顯這似乎是問題所在。我認爲,當你使用getline時,它必須等待用戶輸入,我錯了嗎?

+0

有一個問題在你的循環,它的無盡! – vishal

+0

@vishal大聲笑我知道它無盡的。我有一個if語句在那裏打破循環 – krazibiosvn

+0

不,它不會打破循環 – vishal

回答

1

它有時會發生。要處理的唯一方法是在cin.getline()之前撥打cin.get()。在cin.getline()之前有另一種方法調用cin.flush(),但它可能不起作用。

while (1) 
    { 
     // Reset the input each loop 
     inputMenu = "ABC"; 

     // Menu 
     cout << "Menu\n P (Purchase)\n S (Shut down)" << "\n\n You decide: "; 

     /* I put this if statement as a test, to make sure that it always runs getline. 
     But for some odd reason when I run it I get this (see run below)*/ 


     cin.get(); // add extra input 
     getline(cin, inputMenu); 

     //Blah blah all the other stuff if they enter a P or S. 

     cout << "\nYou just earned " << inputYogurt << " stamps!" 
      << " Bringing your grand total to " << numStamps << "!\n" << endl; 
     } 
    } 

或嘗試使用

cin.ignore(1000, '\n'); 

getline(cin, inputMenu); 
+0

仍然沒有工作:'(我正在考慮使用'cin >>',但我沒有足夠的知識它/你知道你是否可以將它應用到一個字符串上 – krazibiosvn

+0

你可以嘗試添加另一個額外的cin.get()或cin.flush() – Mykola

+0

或者只是使用gets或scanf – Mykola