C++ C+中的用户输入验证测试+;
我对“Bjarne Stroustrup编程原理和使用C++的实践”第5章中的练习9有问题 这一章是关于错误的,练习说“如果结果不能表示为int,请修改练习8中的程序以写出错误” 我试过使用各种不同的C++ C+中的用户输入验证测试+;,c++,validation,input,types,user-input,C++,Validation,Input,Types,User Input,我对“Bjarne Stroustrup编程原理和使用C++的实践”第5章中的练习9有问题 这一章是关于错误的,练习说“如果结果不能表示为int,请修改练习8中的程序以写出错误” 我试过使用各种不同的 if (!cin) error("Input is not an integer"); 然而,我遇到的问题是,如果我读入的不是整数的内容,它将显示所有错误,或者只显示“您想要的值总和大于您输入的值”错误 这是我尝试添加用户输入错误之前练习8中的完整代码: #include <iostre
if (!cin)
error("Input is not an integer");
然而,我遇到的问题是,如果我读入的不是整数的内容,它将显示所有错误,或者只显示“您想要的值总和大于您输入的值”错误
这是我尝试添加用户输入错误之前练习8中的完整代码:
#include <iostream>
#include "../../std_lib_facilities.h"
int main()
{
try {
int size = 0;
int numbers = 0;
int sum = 0;
vector<int>values;
cout << "Please enter how many numbers you want to sum\n";
cin >> size;
if (size < 1)
error("you have to enter at least one value!");
cout << "enter some integers and then | to sum them\n";
while (cin >> numbers)
values.push_back(numbers);
if (values.size() < size)
error(" You wanted to sum more values than you entered. ");
cout << "the sum of the first " << size << " numbers ( ";
for (int i = 0; i < size; ++i) {
sum += values[i];
cout << values[i] << " ";
}
cout << ") is : " << sum << "\n";
return 0;
}
catch (exception& e) {
cerr << "Error: " << e.what() << "\n";
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops: Unknown exception!\n";
keep_window_open();
return 2;
}
}
#包括
#包括“../../std_lib_facilities.h”
int main()
{
试一试{
int size=0;
整数=0;
整数和=0;
向量值;
大小;
如果(尺寸<1)
错误(“必须至少输入一个值!”);
cout>数字)
值。推回(数字);
if(values.size() cout我认为您可以使用cin.fail()
方法来检测错误的输入
比如说
int numbers = 0;
cin >> numbers;
if (cin.fail())
{
/* run when the input is not integer. */
}
什么是error()
,您希望它做什么?@SamVarshavchik error()是来自“../../std_lib_facilities.h”的函数。不幸的是,此文件“std_lib_facilities.h”仅存在于您的计算机上,而不存在于其他任何计算机上,并且您的语句“error()是来自“../../std_lib_facilities.h”的函数没有告诉任何人任何有用的东西,也没有解释你的问题。