Sign in to follow this  

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

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

This topic is 4303 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this