-1

So I have been writing a procedure, inside which I need to take input of two variables, int data and int index. Inside my main function, I have a while loop which takes input until a non integer value is entered.

The problem: When I call the procedure before the while loop inside the main function, everything works fine. However, when I call the procedure after the while loop, the console does not ask me for inputting int data and int index. I don't understand why?

What do I know so far and what I have tried: I have faced a similar problem with the getline() function for strings, and I was able to solve it with cin.ignore(), however, I cannot solve this one with cin.ignore(). I read quite a lot of related posts, but still can't figure it out.

My code

#include<iostream>
using namespace std;

void proced() {
    int data, index;
    cin >> data >> index;
    cout << "this is data: " << data << endl;
    cout << "this is index: " << index << endl;
}
int main() {
    int temp;
    int dance=0;
    while (cin >> temp) {
        dance = temp;
    }
    cout << "this is dance: " <<dance<< endl;
    proced();
}

output when procedure is called after while loop

input: 1 2 3 4 5^Z
output:
this is dance: 5

this is data: -858993460

this is index: -858993460
output when procedure is called before while loop

input: 1 2 3 4 5^Z
output:
this is data: 1

this is index: 2

this is dance: 5

Ps. I am coding in visual studio 2019

1 Answers1

0

1. case with proced() after while

cin.ignore() is right way to go, you just might missed something. Here's my understanding and solution:

The while (cin >> temp) { in your code breaks not because of eof but because of fail. It's easy to check by slightly modifying your code:

    while ( !cin.eof() ) {
        cin >> temp;
        if (cin.fail()) {
            cin.clear(); // clear fail flag
            cin.ignore(cin.rdbuf()->in_avail()); // ignore the rest in input
            break;
        }
        dance = temp;
    }

When you debug the input 1 2 3 4 5^Z it will go inside fail enclose. Now to make cin process next input correctly the fail flag should be cleared and failed data ignored, which is done by code inside if(cin.fail())

The call cin.rdbuf()->inavail() in your test is equal to 1 which is length of faulty input ^Z.

2. case with proced() before while :

First 2 numbers go to data and index then the while executes and reach the fail() part.

Results are different but logic is same.

These StackOverflow posts have a lot of information related to your issue:

How to handle wrong data type input

How to test whether stringstream operator>> has parsed a bad type and skip it

How do I flush the cin buffer?

StahlRat
  • 1,199
  • 13
  • 25