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

Started by
2 comments, last by Plasmarobo 18 years, 1 month ago
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?
Advertisement
It generally looks like:

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

This way, there are no leftover newlines after reading.
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).
use
using namespace std;
to make life eaiser.
and yes, strings help
___________________________________________________Optimists see the glass as Half FullPessimists See the glass as Half EmptyEngineers See the glass as Twice as big as it needs to be

This topic is closed to new replies.

Advertisement