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...
Simple C++ problem - Re: cin.getline and \n
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.
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?
It generally looks like:
std::string name;
std::getline( std::cin, name );
This way, there are no leftover newlines after reading.
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).
And yes, you should use a std::string object to hold the line (and therefore the free function to read in).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement