gpt4 book ai didi

c++ - 检查 cin 输入流产生一个整数

转载 作者:IT老高 更新时间:2023-10-28 23:11:11 28 4
gpt4 key购买 nike

我正在输入这个,它要求用户输入两个整数,然后它们将成为变量。从那里它将执行简单的操作。

如何让计算机检查输入的内容是否为整数?如果没有,请用户输入一个整数。例如:如果有人输入“a”而不是 2,那么它会告诉他们重新输入一个数字。

谢谢

 #include <iostream>
using namespace std;

int main ()
{

int firstvariable;
int secondvariable;
float float1;
float float2;

cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;

cout << "Time for some simple mathematical operations:\n" << endl;

cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;

}

最佳答案

你可以这样检查:

int x;
cin >> x;

if (cin.fail()) {
//Not an int.
}

此外,您可以继续获取输入,直到通过以下方式获得 int:

#include <iostream>



int main() {

int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;

return 0;
}

编辑:要解决下面关于 10abc 等输入的评论,可以修改循环以接受字符串作为输入。然后检查字符串中是否有任何字符而不是数字并相应地处理这种情况。在那种情况下不需要清除/忽略输入流。验证字符串只是数字,将字符串转换回整数。我的意思是,这只是即兴表演。可能有更好的方法。如果您接受 float / double ,这将不起作用(必须在搜索字符串中添加“.”)。

#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;
}

关于c++ - 检查 cin 输入流产生一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18728754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com