1
votes

When dealing with reading different types of input from cin, I've originally thought to start to read as if the input is an integer. If that fails, read it as a string.

It works fine until I tried to read operators such as "+", "-". After entering into the if (!fail), it asks for another input as if the input (operators such as "+", "-") is gone. While, the input should not even been read in.

Here is the code:

 void RPNCalc::run()
 {
    int numInput; bool boolInput = false; string stringInput; char charInput;
    while (stringInput != "quit")
    { 
        cin >> numInput;
        if (!cin)
        {
            cout << "not an int" << endl;
            cin.clear();
            cin >> stringInput;
            cout << stringInput << endl;
            readNonNumInput(stringInput, boolInput);
        } 
        else
        {
            Datum temp = Datum(numInput);
            calculator.push(temp);
        } 
    }
 }

When reading operators into cin, after it fails to read it as an integer, it somehow loses the operators in the buffer. For example, if I enter a "+", it fails to be read as an integer, so it will print the statement "not an int". However, since the "+" is somehow lost in the buffer, there is nothing to be read into the stringInput. Whereas for other string inputs, it fails to be read as integers and that string still exists in the buffer, which can later be read into the stringInput.

That is my understanding of what is going on here. But I could be wrong.

1

1 Answers

1
votes

Read always a string and then try to convert. "+/-" are consumed while you try to read a number, as they can be part of string representation of a number