lundi 11 mai 2015

C++ - getline stdin EOF not working

I'm new to C++ and I'm working on a basic C++ project.

I have some lines of text (with whitespace in them) that I want to make the program accept from standard input and then stop when it encounters a (simulated) EOF because of a Ctrl + D.

I've looked up and tried the solutions given here and here. They work ie the code in the while loop stops executing after I hit Ctrl + D but for some reason the following lines of code do not get executed.

I've tried various ways to do this but I keep getting the same problem.

string line;
int i = 0;
while (true) {
    if (getline(cin, line)) {
        A[i] = line;
        cout << A[i] << endl; //executes as expected
        i++;
    } else {
        break;
    }
}
cout << "exited" << endl; //not executed even after ctrl+d

Here's another method I tried:

string line;
int i = 0;
while (getline(cin, line)){
    //cin.ignore();
    A[i] = line;
    cout << A[i] << endl; //executes as expected
    i++;

}
cout << "exited" << endl; //still not executed


Sample input:

DUCHESS 26
MARIE 8
BERLIOZ 8
TOULOUSE 7
THOMAS 28


PS: I use Eclipse CDT on Ubuntu.

Thanks in advance for any help you can offer.

Aucun commentaire:

Enregistrer un commentaire