简体   繁体   中英

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++".

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".

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:

#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.

for example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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