问题
I am writing a program that allows a student to write a question and store that Question (or string) in a variable, can anyone please tell me the best way to get user input
thanks for your answers and comments
回答1:
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.
回答2:
use gets() as this sample example shows. it is short & simple with minimum errors.
来源:https://stackoverflow.com/questions/7944861/getting-user-input-in-c