Buzzuka
Buzzuka

Reputation: 7

cin won't stop after file input

I'm trying to use cin to read an int after inputting a file directly from command line. Here is my file:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

They're 81 numbers. Here is the code with problem:

#include <iostream>
using namespace std;

int main()
{
    int array[81];
    for(int i = 0; i < 81; i++)
        cin >> array[i];

    int x = 999;
    cin >> x;
    cout << x << endl;

    return 0;
}

I tried to input the file like this: ./a.out < myfile

However, cin >>won't stop and directly print 999 as output. I've tried cin.clear() and cin.ignore(INT_MAX, 'n') but none of them work. Then I think is there something special to input a file like that, so I type all the 81 numbers after running a.out (not using < myfile to input), if I do this, the program will keep taking input and never stop or print.

I have no clue what I am encountering...?

Upvotes: 0

Views: 509

Answers (1)

R Sahu
R Sahu

Reputation: 206567

cin >> x;

fails and your code fails to detect it. Use:

if ( cin >> x )
{
   // Reading to x was successful. Use it.
   cout << x << endl;
}
else
{
   // Reading to x was not successful. Figure out what to do.
}

As a general principle, check the status of every IO call. Be prepared to deal with failure after every such call. Do not use any data you expect to get from an IO operation until you have verified that the call succeeded. That will save you a lot of heartache in the long run.

Upvotes: 2

Related Questions