in the code below the value of int x is always 1.
This leads me to believe that getline(openfile, string) reads in the whole file instead of a line at a time.
If so is this the correct behaviour and how do I just read in a line at a time from a file ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <string>
#include <iostream>
#include <fstream>
usingnamespace std;
int main() {
ifstream in("/etc/hosts");
string s, line;
int x=1;
while(getline(in, line))
cout << x << "\t" << line << endl;
x += 1;
}
Do you understand what do you do?
Your are trying to open file with name "testfile.txt"
Then you check that opening file is success. In your case it's so, you opened file successfully and after that you call getline in loop. Where is problem?
Or did you mean your problem with /etc/hosts?
And did you try to run program with sudo?
unfortunately your amendment (line 15) still gives the same output.
Regarding the problem, I'm learning c++ and I want to understand why getline reads in the whole file at once rather than reading one line at a time.
If it was reading one line at a time then each line in the output would start with the value of x, which would increment, however x is staying at 1 which leads me to believe that the while loop is only getting called once. Does that make sense ?
I know I can get the output desired by using vectors but I can't see why it's not working with getline.