I'm validating string input in C++, to make sure that the input is not empty. I know how to do it using the empty() function with getline(), but I want to know why it's not working when I use cin. When I use empty() with cin, I press enter to try and skip the input, but the empty() never returns true, so I never get re-prompted to enter the string. Is this because the '\n' left in the buffer from cin is counted? I would greatly appreciate the explanation for this.
string name; cout << "Enter your name: "; cin >> name; while (name.empty()) { cerr << "Name can't be empty" << '\n'; cout << "Enter your name: "; cin >> name; }
name.size()the answer should be obvious.std::cinin both cases. In one case it's formatted input (skipping whitespaces) and in the other, it's not.>>also STOPS reading on whitespace. If the name entered is "John Smith",cin >> namewill read "John" intonameand leave " Smith" (note the space!) to be found by a future read. To get "John Smith" you would needcin >> first_name >> last_name, but this leads to little booby traps with names like "Victor von Doom". Often you'll find yourself wanting to read names by sucking in an entire name withgetlineand praying you don't have to think too hard about how to interpret it