reading line by line c++

So I'm reading from .txt file:
My first line looks like: 16 5 12 18 3 14 12 8
My second line looks like: 5 12 8


1
2
3
4
5
6
7
8
9
10
11
12
if (infile.is_open() && infile.good()) {
string line1 = "";
string line2 = "";
cout<<"Enter values:"<<endl;
while (getline(infile, line1)){
cout << line1 << '\n';
} 
cout<<"Enter values to remove: "<<endl;
while (getline(infile, line2)){
cout << line2 << '\n';
}
}


So far my programs runs like:
Enter values:
16 5 12 18 3 14 12 8
5 12 8
Enter values to remove:

I want it to run like:
Enter values:
16 5 12 18 3 14 12 8
Enter values to remove:
5 12 8

please help!!!!
Last edited on
someone please help!!
You should only put std::getline() in a while() loop when you don't know how many lines you will read, and you decide to read them all, right to the end of the file.

However in this case you know that you want to read a total of two lines: one in line1 and the other in line2.

So simply use the std::getline() outside a while() loop.
Also, practice and improve your indent style (it will make the code easier to read).

1
2
3
4
5
6
7
8
9
10
11
if (infile.is_open() && infile.good()) {
    string line1 = "";
    string line2 = "";

    cout<<"Enter values:"<<endl;
    getline(infile, line1);
    cout << line1 << '\n';
    cout<<"Enter values to remove: "<<endl;
    getline(infile, line2);
    cout << line2 << '\n';
}
Topic archived. No new replies allowed.