When and why do I need to use cin.ignore() in C++?

Ignore is exactly what the name implies. It doesn’t “throw away” something you don’t need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint. It works with both input and output buffers. Essentially, for std::cin statements you use ignore before you do … Read more

How do I flush the cin buffer?

I would prefer the C++ size constraints over the C versions: // Ignore to the end of file std::cin.ignore(std::numeric_limits<std::streamsize>::max()) // Ignore to the end of line std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ‘\n’)

std::cin input with spaces?

It doesn’t “fail”; it just stops reading. It sees a lexical token as a “string”. Use std::getline: #include <string> #include <iostream> int main() { std::string name, title; std::cout << “Enter your name: “; std::getline(std::cin, name); std::cout << “Enter your favourite movie: “; std::getline(std::cin, title); std::cout << name << “‘s favourite movie is ” << title; … Read more

How to accept a string and an int using cin?

This is one of the few cases where I’d say a regex is by far your best solution. You could use a regex like: ^\s*([a-zA-Z]+)\s*(\d+)\s*$ Then use regex_match to check it. So for an input string foo: smatch bar; if(regex_match(foo, bar, regex{“^\\s*([a-zA-Z]+)\\s*(\\d+)\\s*$”})) { cout << “OK: ” << bar[1] << ‘\t’ << bar[2] << endl; … Read more