0

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?

Gary
  • 13,303
  • 18
  • 49
  • 71
user3022426
  • 49
  • 2
  • 8
  • possible duplicate of [Is there a C++ iterator that can iterate over a file line by line?](http://stackoverflow.com/questions/2291802/is-there-a-c-iterator-that-can-iterate-over-a-file-line-by-line) – VP. Jun 19 '15 at 20:50
  • possible duplicate of [Read from a file line by line](http://stackoverflow.com/questions/26953360/read-from-a-file-line-by-line) – Galik Jun 19 '15 at 20:56
  • You should search StackOverflow first. There are a plethora of answers already. Try this in your search bar: stackoverflow c++ read file space separated". – Thomas Matthews Jun 19 '15 at 21:26

1 Answers1

2

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.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
alifirat
  • 2,899
  • 1
  • 17
  • 33
  • Worth adding the simplest way to split by space on the line: `stringstream ss(line); while (ss>>token) {/* do stuff */}` – user4581301 Jun 19 '15 at 21:18