2016-09-29 34 views
0

我想檢查兩個單獨的輸入,如果他們是整數或不。我能夠錯誤地檢查一個輸入,但我不太確定如果我使用'get'函數並且兩個輸入都來自'cin'流,如何檢查兩個單獨的輸入。使用C++。錯誤檢查兩個單獨的輸入

我檢查一個整數的代碼顯示如下。

#include <iostream> 
using namespace std; 

int main() { 
int input; 

cout << "Enter an integer: "; 
cin >> input; 

char next; 
int x=0; 

int done = 0; 

while (!done){ 
    next = cin.get(); 
    if (next == ' ' || next == '\n'){ 
     cout << "The Integer that you have entered is: " << input << "\n"; 
     done = 1; 
    } 
    else if (next == '.'){ 
     cerr << "Error: Invalid Input. Not an Integer." << "\n"; 
     done = 1; 
    } 
    else{ 
     cerr << "Error: Invalid Input. Not a number." << "\n"; 
     done = 1; 
    } 
} 

return 0; 
} 
+0

使用'std :: getline'而不是'operator >>'。 –

+0

並退出使用名稱空間標準..原因? [Here](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – amanuel2

+0

@ amanuel2儘管有其他文章,但實際上沒有理由不使用整個名稱空間在這個特殊情況下。 –

回答

0

那麼你可以使用>>int一路過關斬將,拋棄所有東西get()和字符處理,並檢查cin.fail()。例如(我將離開這個工作到你的程序,並在一個循環中重複它作爲一個練習你):

int x; 
cin >> x; 
if (cin.fail()) 
    cout << "Not a valid integer." << endl; 

您可以處理以完全相同的方式,所有後續的輸入。沒有理由只將operator >>限制爲第一個輸入。

+0

謝謝,這工作完美。 –