Reading words with trailing whitespace

B

Brad Marts

I am trying to read a file one word at a time, doing something with
each word in between each read. When the file has trailing
whitespace at the end of the last word, I wind up getting it twice.

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

int main()
{
string str;
ifstream in("test.txt");

while(!in.eof())
{
in >> str;
// Do something with str, e.g.:
cout << str << " ";
}
cout << "\n";
in.close();
return 1;
}

If "test.txt" is:
this is a test

with whitespace after test,

The output is:
this is a test test

I know the problem is coming from the fact that I am not at eof
after reading test and the next read doesn't alter the contents
of str, but I'm not sure of how to make this work.

Thanks,
Brad
 
V

Victor Bazarov

Brad Marts said:
I am trying to read a file one word at a time, doing something with
each word in between each read. When the file has trailing
whitespace at the end of the last word, I wind up getting it twice.

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

int main()
{
string str;
ifstream in("test.txt");

while(!in.eof())
{
in >> str;
// Do something with str, e.g.:
cout << str << " ";
}
cout << "\n";
in.close();
return 1;
}

If "test.txt" is:
this is a test

with whitespace after test,

The output is:
this is a test test

I know the problem is coming from the fact that I am not at eof
after reading test and the next read doesn't alter the contents
of str, but I'm not sure of how to make this work.

Check the result of the operator>> before doing anything with
the 'str'. IOW:

in >> str;
if (in.good())
cout << str << " ";
else
cout << "<DONE>";

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top