c++:仅为cin整数
c++: cin integer only
我试图使用try-catch块验证输入,但遇到了一个小问题。
如果在第一个循环中,用户要输入数字,然后是字母(123abc(,程序会直接跳到第二个循环,不会给出错误,但如果相反(abc123(,则错误消息会正常工作。
此外,如果在输入int时,他们输入了一个双值(45.1(,那么程序将45作为int(x(,将0.1作为double(y(。我需要它抛出错误,或者如果它只是将数字四舍五入到最近的整数值,我会很高兴
代码:
int x;
double y, z;
while (1)
{
try
{
std::cout << "Enter an int (x): ";
if (std::cin >> x && x > 0) { break; }
else if (!std::cin) { throw x; }
else { throw x; }
}
catch (int)
{
std::cout << "Error: Not a valid integer.nn";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
}
while (1)
{
try
{
std::cout << "Enter a double (y): ";
if (std::cin >> y && y > 0) { break; }
else if (!std::cin) { throw y; }
else { throw y; }
}
catch (double)
{
std::cout << "Error: Not a valid double.nn";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
}
z = x + y;
std::cout << "nn" << x << " + " << y << " = " << z;
我会写一个函数,它接受一行输入,从int中提取一个int,并检查是否还有其他垃圾。我使用std::ws
操纵器来消除尾部空白,这不应该是错误
bool parse_int(int& i)
{
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
return (iss >> i && (iss >> std::ws).peek() == EOF);
}
然后将其用作:
int i;
if ( parse_int(i) ) /* ok */
或者,如果您不关心冗余数据,您可以在使用istream::ignore
获得int后忽略它。
此外,抛出算术类型也很奇怪。std::logic_error
异常类的某些子类会更合适。
int main()
{
std::stringstream ss;
int x;
ss << "123abc";
ss >> x;
std::cout << x << std::endl; // 123
// And
ss << "abc123";
ss >> x;
std::cout << x << std::endl; // 0
return 0;
}
流逐个处理每个字符,并根据请求的类型为无效字符停止。
相关文章:
- C++ 读取未知数量的整数到 cin 并输出总和
- C++使用cin给变量一个非整数的值
- C++ Cin 忽略非整数?
- 如何使用 cin 将整数从控制台读取到向量中
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 使用 cin 读取逗号分隔的整数对 (x,y) 和任意空格
- 在C++中使用 cin 同时将整数添加到数组中
- 使用C - CIN获取几个整数数字,然后将它们放入数组中
- C++ cin 无论用户输入什么,都返回 0 作为整数
- 使用 cin.get 获取一个整数
- 为什么cin会将我的双输入转换为整数?C++
- C++:从cin中读取整数行
- 检查C++字符串中的整数:已修订:清除 cin
- 如果 cin 在字符串之前包含整数,则出现打印错误
- 不能在一行中输入 (cin) 超过 10 个整数,以空格分隔到数组中
- 使用 cin.fail() 表示整数与地板
- 为什么这段代码不会使 cin 崩溃?char 输入了一个整数变量 C++
- C++ 使用 cin.ignore() 提取整数时输出奇怪