Jump to content
  • Advertisement
Sign in to follow this  
DrSpock

Simple C++ problem - Re: cin.getline and \n

This topic is 4557 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

Hello guys, i am just learning C++ in general and having read a beginners text and worked through the bits i found intresting, i started messing with my own program ideas etc. But found my progress a little too slow, so im going over my text again doing as many of the excersises as possible. Now i came accross a simple example where i need to request the user input a name.
blah blah snip...

char csName[20];

//Check for a newline and ignore it as its left over from a previous line.
if(cin.peek() == 'n')cin.ignore();   ///<---Heres my minor dilema

cin.getline(csName,20);

blah blah snip...

I was wondering if there is a better way that people generally deal with inputs like this, especially with regards to my method of checking for a leftover newline char?

Share this post


Link to post
Share on other sites
Advertisement
It generally looks like:

std::string name;
std::getline( std::cin, name );


This way, there are no leftover newlines after reading.

Share this post


Link to post
Share on other sites
He's worried about a newline being left over *before* reading. But the solution is, yes, to make that cleanup the responsibility of the previous reader.

And yes, you should use a std::string object to hold the line (and therefore the free function to read in).

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!