如何让这个在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++中处理字符串错误时的错误处理
- 3. C/C++预处理错误
- 4. C++ winform错误处理
- 5. 预处理器错误C++
- 6. 错误文件处理C++
- 7. C fwrite错误处理
- 8. C#OledbException被处理错误
- 9. Stripe C#错误处理
- 10. C#错误处理(NaN)
- 11. C++处理意外错误
- 12. Ajax错误处理C#
- 13. C++文件处理错误
- 14. HTMLAgilityPack Asp.net C#错误处理
- 15. 文件处理C++错误
- 16. C处理器错误
- 17. 错误处理在C(文件)
- 18. 在python中处理c库错误?
- 19. 在C中错误处理mkdir和chdir?
- 20. 处理错误
- 21. 错误处理
- 22. 处理错误
- 23. 处理错误
- 24. 处理错误
- 25. 错误处理
- 26. 错误处理
- 27. 处理错误
- 28. 处理错误
- 29. 处理 - 错误
- 30. C++ API设计和错误处理
究竟你 “只接受整数” 是什么意思?具体而言,如果用户输入其他内容(例如,字母或标点符号),您希望发生什么? – 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