For veterans of C++, is getline your preferred way of getting user input?
Having a preference can be troubling; there are times when you'll be working a square peg into a round hole because you want the program to work according to said preference. Since cin is line buffered though, using std::getline makes a lot of sense, most of the time.
? What if you're dealing with both numbers and strings?
Convert where necessary.
Finally, if you're going to be using getline and risk stuff left in the buffer, is there a function that you can easily put in code to auto clear it as you go?
std::getline will read entire lines if you do not change the delimiter from the default one, which is \n or EOF or something like that, so there is no left over input to be read. It's when you change the delimiter that you need to be more careful. In particular, if the input is not good, then you will have problems arising from those errors.
One way to do what you want is to validate the string before you split it up. This means that the input device doesn't need to actually split it, and there will be less errors related to that from the input device.
Code:
#include <string>
#include <sstream>
#include <iostream>
bool isformatted(const std::string& input);
int main() {
std::string last, first, middle;
std::string name;
do {
std::cout << "Enter your name last, first middle:\n";
getline(std::cin, name);
} while ( !isformatted(name) );
std::istringstream splitter(name);
std::getline(splitter, last, ',');
splitter >> first >> middle;
std::cout << "You entered: " << first << ' ' << middle << ' ' << last << std::endl;
}
bool isformatted(const std::string& input) {
return input.find(", ") != std::string::npos && input.find_last_of(' ') != std::string::npos;
}
#if 0
my output
Enter your name last, first middle:
John Q. Public
Enter your name last, first middle:
Public, John Q.
You entered: John Q. Public
#endif