我试着从标准输入中读取整数,我有这样的代码,如果用户输入字母,它就会再次提示。但是,如果用户输入像6.9这样的浮点数,就会被接受为有效的输入,并且函数结束。
int nr=0;
std::cout << "Vector length: ";
std::cin >> nr;
while (std::cin.fail() ) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), '\n');
std::cout << "Input is not number , try one more time: ";
std::cin >> nr;
}我想检测所有错误的输入。如何更改代码以将浮点数视为无效?
发布于 2014-05-20 20:04:57
做以下工作:
int nr = 0;
std::cout << "Vector length: ";
while (!(std::cin >> nr)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), '\n');
std::cout << "Input is not number , try one more time: ";
}然而,上述代码将适用于浮点数(例如,"9.8")。如果输入EOF,它还会创建一个无限循环。如果您想要严格的积分值,请执行以下操作:
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>
bool is_number(const std::string& s)
{
return !s.empty() && std::find_if(s.begin(),
s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}
int main()
{
std::string num;
std::cout << "Vector length: ";
std::getline(std::cin, num);
while (!is_number(num)) {
std::cout << "Input is not number , try one more time: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), '\n');
num.clear();
std::getline(std::cin, num);
}
return 0;
}https://stackoverflow.com/questions/23768783
复制相似问题