如何解决在C++中使用cin在int变量中输入char和int
我正在编写代码以从用户那里获取一个整数 ID,该 ID 稍后会从文件中进行验证。 现在,当我没有在 cin 中输入有效的输入时,它不起作用(显然)。我在下面附上了一个示例代码:
std::cout << "Enter ID : " << std::endl;
std::cin >> id;
就这么简单。
现在,如果我输入像 a
或任何其他字符这样的输入,我可以使用 cin.fail() 检查任何错误
但是如果我输入像 11a
这样的输入似乎不起作用。我在互联网上搜索了很多,但找不到任何合适的解决方案。
解决方法
首先欢迎使用 Stack。试试这个
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin,theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin,theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
我做了一个输出来可视化它。变量“inputAsInt”将是您必须进一步处理的变量。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。