如何讓這個在CIN聲明只接受整數?錯誤在C++處理
錯誤在C++處理
回答
我不認爲你可以強制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";
}
「我不認爲你可以做全球這樣的事情」,你可以設置'cin.exception(IOS :: failbit)'在全球範圍內應用它。 – ybungalobill 2010-09-29 19:18:01
@ybungalobill即使有例外面膜,可以成功地讀取其他類型('的std ::字符串s;給std :: cin >> S;')。據我所知,當試圖讀取非整數類型(即使輸入的格式正確)時,也無法強制'operator >>'*總是*失敗。 – 2010-09-29 19:25:21
啊,我看到現在的措詞是如何混淆了。編輯。 – 2010-09-29 19:27:31
把CIN在while循環和測試。
cin.exceptions(ios::failbit | ios::badbit);
int a;
bool bGet = true;
while(bGet)
{
try
{
cin >> a;
bGet = false;
}
catch
{ ; }
}
'運營商>>'除非你設置了具有ios ::例外 – 2010-09-29 19:17:21
像編輯一個標誌不扔在這種情況下的例外? – Jess 2010-09-30 04:23:41
#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/ 我需要做的這只是昨天:)
另一種使用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
- 1. 在C++中處理字符串錯誤時的錯誤處理
- 2. C/C++預處理錯誤
- 3. C處理器錯誤
- 4. C#錯誤處理(NaN)
- 5. C fwrite錯誤處理
- 6. 錯誤文件處理C++
- 7. 錯誤處理在C(文件)
- 8. 在C中錯誤處理mkdir和chdir?
- 9. 在python中處理c庫錯誤?
- 10. 處理錯誤
- 11. 錯誤處理
- 12. 處理錯誤
- 13. 錯誤處理
- 14. 處理錯誤
- 15. 錯誤處理
- 16. 在VBScript中處理錯誤?
- 17. 在PHP中處理錯誤
- 18. 在fphttpclient中處理錯誤?
- 19. 在rails中處理錯誤
- 20. 處理錯誤在JavaScript
- 21. 在Kivy中處理錯誤
- 22. 在javascript中處理錯誤
- 23. 在SQLAlchemy中處理錯誤
- 24. ContractFilter在EndpointDispatcher(錯誤處理)
- 25. 在處理多個錯誤
- 26. 在突變處理錯誤
- 27. 在HAPI中處理錯誤
- 28. 在API中處理錯誤
- 29. 在MVC中處理錯誤
- 30. 在PHP中處理錯誤
究竟你 「只接受整數」 是什麼意思?具體而言,如果用戶輸入其他內容(例如,字母或標點符號),您希望發生什麼? – 2010-09-29 19:02:13
http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad-cin-input – karlphillip 2010-09-29 19:20:55
的'cin'是一個通用的對象,你不能將它修改爲只提供整數。你可以修改你的程序只接受整數。可以編寫自己的'cin'過濾版本,或者寫一些只從文件中取整數並將文件傳遞給程序的文件。 – 2010-09-29 19:52:26