2010-09-29 89 views
0

如何讓這個在CIN聲明只接受整數?錯誤在C++處理

+1

究竟你 「只接受整數」 是什麼意思?具體而言,如果用戶輸入其他內容(例如,字母或標點符號),您希望發生什麼? – 2010-09-29 19:02:13

+0

http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad-cin-input – karlphillip 2010-09-29 19:20:55

+0

的'cin'是一個通用的對象,你不能將它修改爲只提供整數。你可以修改你的程序只接受整數。可以編寫自己的'cin'過濾版本,或者寫一些只從文件中取整數並將文件傳遞給程序的文件。 – 2010-09-29 19:52:26

回答

5

我不認爲你可以強制std::cin拒絕接受在所有情況下非整數輸入。你可以隨時寫:

std::string s; 
std::cin >> s; 

因爲字符串不關心輸入的格式。但是,如果你想測試是否讀取整數成功可以使用fail()方法:

int i; 
std::cin >> i; 
if (std::cin.fail()) 
{ 
    std::cerr << "Input was not an integer!\n"; 
} 

或者,你可以測試cin對象本身,這是等價的。

int i; 
if (std::cin >> i) 
{ 
    // Use the input 
} 
else 
{ 
    std::cerr << "Input was not an integer!\n"; 
} 
+1

「我不認爲你可以做全球這樣的事情」,你可以設置'cin.exception(IOS :: failbit)'在全球範圍內應用它。 – ybungalobill 2010-09-29 19:18:01

+0

@ybungalobill即使有例外面膜,可以成功地讀取其他類型('的std ::字符串s;給std :: cin >> S;')。據我所知,當試圖讀取非整數類型(即使輸入的格式正確)時,也無法強制'operator >>'*總是*失敗。 – 2010-09-29 19:25:21

+0

啊,我看到現在的措詞是如何混淆了。編輯。 – 2010-09-29 19:27:31

-1

把CIN在while循環和測試。

cin.exceptions(ios::failbit | ios::badbit); 
int a; 
bool bGet = true; 
while(bGet) 
{ 
    try 
    { 
    cin >> a; 
    bGet = false; 
    } 
    catch 
    { ; } 
}  
+0

'運營商>>'除非你設置了具有ios ::例外 – 2010-09-29 19:17:21

+0

像編輯一個標誌不扔在這種情況下的例外? – Jess 2010-09-30 04:23:41

4
#include <iostream> 
#include <limits> 
using namespace std; 

int main(){ 
    int temp; 
    cout << "Give value (integer): "; 
    while(! (cin >> temp)){ 
     cout << "That was not an integer...\nTry again: "; 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 
    cout << "Your integer is: " << temp; 
} 

發現這個源來自:http://www.dreamincode.net/forums/topic/53355-c-check-if-variable-is-integer/ 我需要做的這只是昨天:)

0

另一種使用std :: cin的方法。

#include <iostream> 
#include <limits> 

using namespace std; 

int main() 
{ 

    double input; 
    while (cin) 
    { 
     cout << "Type in some numbers and press ENTER when you are done:" << endl; 
     cin >> input; 
     if (cin) 
     { 
      cout << "* Bingo!\n" << endl; 
     } 
     else if (cin.fail() && !(cin.eof() || cin.bad())) 
     { 
      cout << "* Sorry, but that is not a number.\n" << endl; 
      cin.clear(); 
      cin.ignore(numeric_limits<std::streamsize>::max(),'\n'); 
     } 
    } 
} 

G ++ -o NUM num.cpp