Why is it good to read numeric data with char before convering to int?

It is a question my teacher ask.
I have no idea about this.
closed account (3qX21hU5)
Huh? I don't see why you would do this other then maybe to handle user error when they enter a letter instead of a number but that can be handled in much better ways I would believe.

I would tell the professor your shouldn't do it. It is just a unneeded step and there are better way to handle stream errors when the user enters a char instead of a number for a int variable.

Here is a example of how you can safeguard a stream from going into error if the user doesn't enter a number into a int.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <limits>

using namespace std;

int main ()
{
    int number;

    cout << "Please enter a number: ";
    cin >> number;

    // Will run so long as the steam is in error like when
    // the user enters a character instead of a number or a string instead
    // of a number
    while (cin.fail())
    {
        cout << "Error! You most likely didn't enter a number!" << endl;
        cout << "Please try again" << endl;
        
        // Fixes the error and then clears the error state of the stream.
        cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
        cin.clear();

        cout << "Please enter a number: ";
        cin >> number;
    }

    return 0;
}




Topic archived. No new replies allowed.