在 C++ 中使用 cin 在 int 变量中输入 char 和 int
Inputting char and int in int variable using cin in C++
我正在编写代码以从用户那里获取一个整数 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”将是您必须进一步使用的变量。
我正在编写代码以从用户那里获取一个整数 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”将是您必须进一步使用的变量。