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

时间:2016-05-21 16:13:22

标签: c++ string std user-input getline

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

例如:

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;

当我运行代码时,在输入姓氏后按Enter键后,它只是开始一个新行,我必须输入另一个输入才会询问年龄输入。

我听说混合getline和cin是不好的,并且使用其中一个更好。我能做些什么来完成这项工作以及将来的良好做法?

编辑:我在最初搜索解决方案时添加了忽略,因为没有它们,代码就不会等待用户输入。输出将是&#34;输入名字:输入姓氏:&#34;

Edit2:已解决。问题是我用过&#34; cin&gt;&gt;&#34;在我的代码中,用户输入一个int变量并需要第一个cin.ignore语句,而不是另一个。没有包含代码的那部分,因为我不知道这会影响它。对所有这些仍然是新的,所以感谢大家的帮助!

3 个答案:

答案 0 :(得分:2)

您的>>来电没有帮助您。仅在输入未提取行尾字符(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::ignore

您只需std::cin >> age;之后的std::getline来电,因为这不会删除行尾字符,而DemoApplication来电则会删除。

答案 1 :(得分:1)

我建议删除ignore函数调用:

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

答案 2 :(得分:1)

根据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

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