1

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
kac26
  • 381
  • 1
  • 7
  • 25

1 Answers1

2

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;
}
Smeeheey
  • 9,906
  • 23
  • 39