Question

I have a text file

0 Po Tom Mr 123AlphabetStreet Netherlands Wulu 123456 D01 Malaysia SmallAdventure 231112 
0 Liu Jack Mr 123AlphabetStreet Italy Spain 123456 D02 Afghanistan TriersAdventure 030214

I am trying to read the txt file:Form.txt, store each line using getline into the variable foo

This is the working program

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
   fstream afile;
   afile.open("Form.txt",ios::in);

   string foo;


    while (getline(afile,foo,'\n') );
    {
        cout<<foo
            <<endl;

    }

}

Nothing gets printed to the console output , I am expecting

0 Po Tom Mr 123AlphabetStreet Netherlands Wulu 123456 D01 Malaysia SmallAdventure 231112 
0 Liu Jack Mr 123AlphabetStreet Italy Spain 123456 D02 Afghanistan TriersAdventure 030214

Instead i get

What is wrong with my code ??

Was it helpful?

Solution

You have a semicolon at the end of your while loop:

while (getline(afile, foo, '\n'));
//                               ^

This causes the extraction to be performed but only the when the loop ends does foo get printed. The last extraction doesn't extract anything which is why foo is empty, hence the empty output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top