简体   繁体   中英

Read file with multiple spaces word by word c++

I want to read .txt file word by word and save words to strings. The problem is that the .txt file contains multiple spaces between each word, so I need to ignore spaces.

Here is the example of my .txt file:

John      Snow  15
Marco  Polo     44
Arya    Stark   19

As you see, each line is another person, so I need to check each line individualy.

I guess the code must look something like this:

ifstream file("input.txt");
string   line;

while(getline(file, line))
{
    stringstream linestream(line);
    string name;
    string surname;
    string years;

    getline(linestream, name, '/* until first not-space character */');
    getline(linestream, surname, '/* until first not-space character */');
    getline(linestream, years, '/* until first not-space character */');

   cout<<name<<" "<<surname<<" "<<years<<endl;
}

Expected result must be:

John Snow 15
Marco Polo 44
Arya Stark 19

You can just use operator>> of istream , it takes care of multiple whitespace for you:

ifstream file("input.txt");
string   line;

while(!file.eof())
{
    string name;
    string surname;
    string years;

    file >> name >> surname >> years;

    cout<<name<<" "<<surname<<" "<<years<<endl;
}

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