Formatted I/O; taken from Baby's First C++:
#include <string>
#include <iostream>
int main()
{
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Thank you, '" << name << "'." << std::endl;
}
This isn't quite satisfactory, as many things can (and thus will) go wrong. Here's a slightly more watertight version:
int main()
{
std::string name;
int score = 0;
std::cout << "Enter your name: ";
if (!std::getline(std::cin, name)) { /* I/O error! */ return -1; }
if (!name.empty()) {
std::cout << "Thank you, '" << name << "', you passed the test." << std::endl;
++score;
} else {
std::cout << "You fail." << std::endl;
--score;
}
}
Using getline()
means that you might read an empty line, so it's worthwhile checking if the result is empty. It's also good to check for the correct execution of the read operation, as the user may pipe an empty file into stdin, for instance (in general, never assume that any particular circumstances exist and be prepared for anything). The alternative is token extraction, std::cin >> name
, which only reads one word at a time and treats newlines like any other whitespace.