Jump to content
  • Advertisement
Sign in to follow this  
spraff

std::cin gives duplicate input at EOF

This topic is 4042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here's a snippet to demonstrate the effect:
#include <iostream>
#include <string>

int main () {
	std::string s;
	while (std::cin) {
		std::cin >> s;
		std::cout << "Echoing " << s << '\n';
	}
}

Here's what happens on the command line when I press a[enter]b[enter]c[enter][ctrl-d]
Quote:
a Echoing a b Echoing b c Echoing c Echoing c
Here's what happens on the command line when I press a[enter]b[enter]c[ctrl-d][ctrl-d] (just one ctrl-d doesn't work).
Quote:
a Echoing a b Echoing b cEchoing c Echoing c
And whith a file test.input whose contents are "a\nb\nc", here's the output of "./a.out < test.input"
Quote:
Echoing a Echoing b Echoing c Echoing c
This is causing difficulties. Am I using while(std::cin) incorrectly or something? What's the sense in the duplicate line? Thanks already.

Share this post


Link to post
Share on other sites
Advertisement
Before EOF is read, std::cin is still in a good state. So you enter the loop one last time where you don't mean to.

Inside the loop nothing is read in to s, because you'll hit EOF immediately and so s contains the same string as before. Thus you get a repeat print-out of that string.

Try this:


#include <iostream>
#include <string>

int main () {
std::string s;
while (std::cin >> s)
std::cout << "Echoing " << s << '\n';

return 0;
}



Edd

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!