Search code examples
c++fileioifstreamgetline

Why is my program reading more than just the first line of my txt file?


I'm having trouble grabbing the first line of txtfile.txt. I've tried changing the number in the second parameter and completely removing it. Nothing has worked and for some reason I cannot grab the 1 alone.

int main() {
ifstream fin; 
char ex1[100];
fin.open("txtfile.txt");
if (fin.is_open()) {
    cout << "YES FILE OPENED" << endl; //testing if file opened
}
while (fin.peek() != EOF){
    fin.getline(ex1, 100, '\n');
    cout << ex1 << endl;
    }
}

txtfile.txt: below

1
ABC
2

Solution

  • If you want just the first line, break from the while loop after getting the first line:

    while (fin.peek() != EOF){
        fin.getline(ex1, 100, '\n');
        cout << ex1 << endl;
        break;
        }
    }