C++ 判断用户输入的类型时出现的问题
我在判断用户输入的号码类型是否正确时遇到了一些问题 我想设计一个只适用于输入C++ 判断用户输入的类型时出现的问题,c++,C++,我在判断用户输入的号码类型是否正确时遇到了一些问题 我想设计一个只适用于输入int类型编号的程序。当用户输入其他类型(例如,double,char类型)时,系统将输出错误。但是,当用户输入非法类型的值时,系统首先输出enter指令,然后输出错误语句 本部分代码如下: for(int i=0;i
int
类型编号的程序。当用户输入其他类型(例如,double
,char
类型)时,系统将输出错误。但是,当用户输入非法类型的值时,系统首先输出enter指令,然后输出错误语句
本部分代码如下:
for(int i=0;i std::cout为此使用整数流运算符过于简单。如果由于任何原因输入失败,则必须重置错误状态,忽略一些字符并继续读取
更重要的是,如果遇到类似小数点的情况,只要前面出现类似整数的内容就可以了。当然,下一次调用将失败,因为您尝试读取整数,但流中的下一个字符是。
这就是你的情况,你甚至没有试图从错误中恢复
通常,当您请求用户输入时,用户需要在键入值后按Enter键。因此,您可以使用基于行的输入。为此,您可以将std::string
与std::getline
一起使用。一旦您将一行输入作为字符串,就可以轻松地从该字符串中解析所需的值
下面是一个简单的程序,它使用std::stoi
将输入行转换为整数。但是,由于“1.2”仍将正确解析为整数值1,因此添加了一些额外的逻辑,只允许任何剩余字符使用空格
#include <cctype>
#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
std::string line;
while (std::getline(std::cin, line))
{
try {
size_t pos = 0;
int ival = std::stoi(line, &pos);
while (pos < line.size()) {
if (!std::isspace(line[pos]))
throw std::runtime_error("Malformed integer value");
++pos;
}
std::cout << "Integer read: " << ival << '\n';
}
catch(std::exception &e)
{
std::cerr << "Invalid input: " << line << '\n';
}
}
}
#包括
#包括
#包括
#包括
int main()
{
std::字符串行;
while(std::getline(std::cin,line))
{
试一试{
大小\u t pos=0;
int ival=std::stoi(行和位置);
而(位置#include <cctype>
#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
std::string line;
while (std::getline(std::cin, line))
{
try {
size_t pos = 0;
int ival = std::stoi(line, &pos);
while (pos < line.size()) {
if (!std::isspace(line[pos]))
throw std::runtime_error("Malformed integer value");
++pos;
}
std::cout << "Integer read: " << ival << '\n';
}
catch(std::exception &e)
{
std::cerr << "Invalid input: " << line << '\n';
}
}
}