By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 839 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

Reading words with trailing whitespace

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
"Brad Marts" <ma***@phy.duke.edu> wrote...
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
Jul 19 '05 #2

P: n/a
Brad Marts wrote:
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.


Does this answer your question?
http://www.parashift.com/c++-faq-lit....html#faq-15.5

Jul 22 '05 #3

P: n/a
On Tue, 18 Nov 2003 00:00:51 +0100, Nudge wrote:
Brad Marts wrote:
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.


Does this answer your question?
http://www.parashift.com/c++-faq-lit....html#faq-15.5


Yes, it does. Thank you. Even after reading the faq for some time I still
missed it.
Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.