user3022426
user3022426

Reputation: 49

Reading text file line by line in c++

I want to read text from text file into my c++ code. Here is my code:-

f.open(input);
if (f)
{   
    while(!f.eof())
    {
        LinkedList obj;
        string c, d, l;
        f>>c>>d>>l;

        nodes.push_back(c);
        nodes.push_back(d);

        vector<string> temp;
        temp.push_back(c);
        temp.push_back(d);
        temp.push_back(l);
        vecNodes.push_back(temp);
    }
 }

My text file is below:

a b c
a c
d e
e
g h a

My question is how can I read one line at one time. When my code read the second line it go also read the first character of third line Which is wrong. I know I can put delimiter at the end of each line which might work. Is there any other way to do this?

Upvotes: 0

Views: 1255

Answers (1)

alifirat
alifirat

Reputation: 2937

You can read line by line your file with this following code :

string line;
ifstream myfile;
myfile.open("myfile.txt");

if(!myfile.is_open()) {
    perror("Error open");
    exit(EXIT_FAILURE);
}

while(getline(myfile, line)) {
    // do things here
}

Then split by space your string and add your elements in your list.

Upvotes: 2

Related Questions