简体   繁体   English

C++ 中的用户输入验证测试

[英]User input validation test in C++

i'm having trouble with exercise 9 from chapter 5 of "Bjarne Stroustrup Programming Principles and Practice Using C++".我在“使用 C++ 的 Bjarne Stroustrup 编程原则和实践”的第 5 章中的练习 9 中遇到了问题。

The chapter is about errors, and the exercise says " Modify the program from excercise 8 to write out an error if the result cannot be represented as an int".这一章是关于错误的,练习说“如果结果不能表示为int,则修改练习8中的程序以写出错误”。

I have tried using various variations of我尝试使用各种变体

if (!cin)
error("Input is not an integer"); 

However the issue I get is that if I read in something that is not an integer it will then either display all the errors or just the "you wanted to sum more values than you entered" error.但是,我遇到的问题是,如果我读入的不是整数的内容,它要么显示所有错误,要么仅显示“您想对比输入的值求和的值多”错误。

This is my full code from excercise 8 before i tried to add the user input error:这是我在尝试添加用户输入错误之前来自练习 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;
    }
}

I think that you can use cin.fail() method to detect a wrong input.我认为您可以使用cin.fail()方法来检测错误的输入。

for example例如

int numbers = 0;
cin >> numbers;
if (cin.fail())
{
   /* run when the input is not integer. */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM