gpt4 book ai didi

c++ - 如何检查输入是否是没有任何其他字符的有效整数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:52:01 24 4
gpt4 key购买 nike

#include <iostream>
#include <limits>

using namespace std;

int main()
{
int x;
cout << "5 + 4 = ";
while(!(cin >> x)){
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}

如何检查用户输入的整数是否有效?在我上面写的这个程序中,如果用户输入9,它应该是正确的,但是,如果用户输入例如9a,它应该返回一个错误,但是它不是出于某种原因。我该如何纠正它?

我是如何使用 cin.peek() 实现的

#include <iostream>
#include <limits>
#include <stdio.h>

using namespace std;

int main()
{
int x;
bool ok;
cout << "5 + 4 = ";

cin >> x;

while(!ok){
cin >> x;

if(!cin.fail() && (cin.peek() == EOF || cin.peek() == '\n')){
ok = true;
}
else{
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}

if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}

return 0;
}

最佳答案

你可以读取一个字符串,从中提取一个整数,然后确保没有剩下任何东西:

std::string line;
std::cin >> line;
std::istringstream s(line);
int x;
if (!(s >> x)) {
// Error, not a number
}
char c;
if (s >> c) {
// Error, there was something past the number
}

关于c++ - 如何检查输入是否是没有任何其他字符的有效整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20287186/

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