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

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

## 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 on other sites
It generally looks like:

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

This way, there are no leftover newlines after reading.

##### 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 on other sites
use
using namespace std;
to make life eaiser.
and yes, strings help