1
void dr1() {
    int num1 = 0, num2 = 0;
    char str[100];  

    while (str[0] != '|') {
        cout << "Please enter two numbers (enter \"|\" to terminate): ";

        cin >> num1;
        cin >> num2;
        cin.getline(str, 100);

        cout << num1 << num2 << endl;
    }
}

If a user inputs a string, shouldn't the variable str read it from the input buffer?

From what I've learned, you cannot input string characters into an int type and therefore they are left in the buffer. If they are left in the buffer, shouldn't getline() read whatever input is left in the buffer?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
sangmin park
  • 547
  • 3
  • 7
  • 16
  • 1
    Are you asking if the `num` reads fail, shouldn't the line-read consume the line and move on? If so, you need to reset the stream state before the getline, and you need to detect the failure before doing so. – WhozCraig May 29 '18 at 20:33
  • 1
    This might be what you need: https://stackoverflow.com/questions/10828937/how-to-make-cin-take-only-numbers – NathanOliver May 29 '18 at 20:34
  • When you need to do different things based on what the user input, your best options is to read input line by line and process each line using `std::istringstream`. The link posted by @NathanOliver is a good place to start. – R Sahu May 29 '18 at 20:35

1 Answers1

1

If operator>> fails to read a formatted value, the input is indeed left in the buffer, AND ALSO the stream is put into an error state, thus subsequent reads are ignored and also fail. That is why getline() does not read the "|" input as expected. You need to clear() the stream's error state after a formatted read operation fails. For example:

void dr1()
{
    int num1, num2;
    char str[100];
    do
    {
        cout << "Please enter two numbers (enter \"|\" to terminate): " << flush;
        if (cin >> num1)
        {
            if (cin >> num2)
            {
                // use numbers as needed...
                cout << num1 << num2 << endl;
                continue;
            }
        }
        cin.clear();
        if (!cin.getline(str, 100)) break;
        if (str[0] == '|') break;
    }
    while (true);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770