Solution to std::cin problem

After having the same problem with std::getline() in the current program I’m working on, I asked some people and finally someone explained to me why this happened. So I’m posting a quick explanation to this.


In an earlier post about a problem with std::cin that I posted and no one answered, I finally understood why this happens, so this is a quick explanation on the problem.

Aparently the std::cin that goes before the std::getline(std::cin, mszName) leaves a newline in the buffer, ‘\n’, so std::getline() interprets this as user input. So the buffer must be cleared in order for the std::getline() not to be “skipped”. So how exactly does one do this? well it’s pretty simple actually:

#include

#include

int main(){

std::string mszText, mszWord;

std::cout < < “Type a word: “;

std::cin >> mszWord;

std::cin.ignore(); //This clears the buffer
std::cout < < “Type a string: “;

std::getline(std::cin, mszText);

return 0;

}

So by adding std::cin.ignore() after a std::cin and/or before a std::getline() will clean the buffer and won’t “skip” the std::getline().

Thanks to goling from the #c++ channel over at freenode.net for clarifying this to me.

-LMurillo

0 Responses to “Solution to std::cin problem”


  1. No Comments

Leave a Reply




Bad Behavior has blocked 22 access attempts in the last 7 days.