如何获取用户输入的字符串然后是 int?

How do I get user inputs for a string and then an int?

我有一个数据库 class,它是一个包含许多对象的数组。 该函数将从用户那里获取一些输入,其中包括字符串和整数

例如:

std::cout << "Enter first name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, first_name);
std::cout << "Enter last name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, last_name);
std::cout << "Enter age: ";
std::cin >> age;

当我 运行 代码时,在我输入姓氏后按回车键后,它只是开始一个新行,我必须在它要求输入年龄之前输入另一个输入。

我听说混合使用 getline 和 cin 不好,最好使用其中之一。我可以做些什么来完成这项工作以及向前推进的好做法是什么?

编辑:我在最初搜索解决方案时添加了忽略,因为没有它们,代码就不会费心等待用户输入。输出将是 "Enter first name: Enter last name: "

Edit2:已解决。问题是我之前在我的代码中使用 "cin >>" 让用户输入一个 int 变量并且需要第一个 cin.ignore 语句,而不是另一个。没有包含那部分代码,因为我不知道那会影响它。对这一切还很陌生,所以感谢大家的帮助!

我建议删除 ignore 函数调用:

std::string name;
std::cout << "Enter name: ";
std::getline(cin, name);
unsigned int age;
std::cout << "Enter age: ";
std::cin >> age;

根据 std::basic_istream::ignore() 的文档,此函数的行为类似于 未格式化的输入函数 ,这意味着它将 阻塞 如果缓冲区中没有可跳过的内容,则等待用户输入。

在您的情况下,您的两个 ignore 语句都不是必需的,因为 std::getline() 不会在缓冲区中留下换行符。所以实际发生的是:

std::cout << "Enter first name: ";
/*your first input is skipped by the next ignore line because its going to block until
input is provided since there is nothing to skip in the buffer*/
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* the next getline waits for input, reads a line from the buffer and also removes the 
new line character from the buffer*/
std::getline(std::cin, first_name);

std::cout << "Enter last name: ";
/*your second input is skipped by the next ignore line because its going to block until
input is provided since there is nothing to skip in the buffer*/
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* the next getline waits for input and this is why it seems you need to provide 
another input before it ask you to enter the age*/
std::getline(std::cin, last_name);

您需要删除 ignore 语句才能使其正常工作。您可能还想阅读 When and why do I need to use cin.ignore() in C++

您的 std::cin::ignore 电话没有帮助您。仅在不提取 行尾 字符 (>>).

的输入后才需要它们
std::string first_name;
std::string last_name;
int age;

std::cout << "Enter first name: ";
std::getline(std::cin, first_name); // end of line is removed

std::cout << "Enter last name: ";
std::getline(std::cin, last_name); // end of line is removed

std::cout << "Enter age: ";
std::cin >> age; // doesn't remove end of line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // this does
// input can proceed as normal

您只需要在 std::cin >> age; 之后调用 std::cin::ignore,因为这不会删除行尾字符,而 std::getline 调用会。