如何获得字符串和int的用户输入

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

本文关键字:用户 输入 int 何获得 字符串      更新时间:2023-10-16

我有一个数据库类,它是一个将容纳许多对象的数组。该函数将接受用户的两个输入,其中包括字符串和int

例如:

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混在一起不好,最好用其中一种。我能做些什么来实现这一目标?今后的良好做法是什么?

编辑:我在最初搜索解决方案时添加了忽略,因为如果没有它们,代码就不会麻烦等待用户输入。输出为"输入名字:输入姓氏:">

第2版:决议。问题是,我在代码的早期使用了"cin>>"让用户输入一个int变量,并且需要第一个cin.ignore语句,但不需要另一个。没有包括代码的这一部分,因为我不知道这会影响它。对这一切来说仍然是新的,所以感谢大家的帮助!

您的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调用会删除。

根据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语句才能使其工作。您可能还想阅读我何时以及为什么需要在C++中使用cin.ignore()

我建议删除ignore函数调用:

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