2011-05-18 64 views
0

我有以下代碼:C++中的cin.get()問題?

#include <conio.h> 
using namespace std; 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
     int x = 0; 
     cout << "Enter x: " ; 
     cin >> x; 
     if (cin.get() != '\n') // **line 1** 
     { 
      cin.ignore(1000,'\n'); 
      cout << "Enter number: "; 
      cin >> x; 
     } 

     double y = 0; 
     cout << "Enter y: "; 
     cin >> y;  
     if (cin.get() != '\n'); // **Line 2** 
     { 
      cin.ignore(1000,'\n'); 
      cout << "Enter y again: "; 
      cin >> y; 
     } 
     cout << x << ", " << y; 

    _getch(); 

    return 0; 
} 

在執行時,我可以輸入x值和它忽略行1如我的預期。但是,當程序要求y值時,我輸入了一個值,但程序沒有忽略,而在第2行?我不明白,第1行第2行有什麼區別?我該如何讓它按預期工作?

回答

8
if (cin.get() != '\n'); // **Line 2** 
// you have sth here -^ 

刪除該分號。如果在那裏,if聲明基本上什麼都不做。
另外,您還沒有測試用戶是否真的輸入了一個數字......如果我輸入'd'而不是? :)

while(!(cin >> x)){ 
    // woops, something has gone wrong... 
    // display a message to tell the user he made a mistake 
    // and after that: 
    cin.clear(); // clear all errors 
    cin.ignore(1000,'\n'); // ignore until newline 

    // and try again, while loop yay 
} 
// now we have correct input.