简体   繁体   中英

Unable to read from text file and store into string

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 ??

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM