首页 文章

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

提问于
浏览
-2

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

例如:

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是不好的,并且最好使用其中一个 . 我能做些什么来完成这项工作以及前进的良好做法?

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

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

3 回答

  • 1

    根据std::basic_istream::ignore()的文档,此函数表现为 Unformatted Input Function ,这意味着它将返回 block 并等待用户输入,如果缓冲区中没有要跳过的内容 .

    在您的情况下,由于 std::getline() 不会将新行字符留在缓冲区中,因此两个 ignore 都不是必需的 . 所以实际发生的是:

    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++

  • 1

    你的 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 调用会执行 .

  • 2

    我建议删除 ignore 函数调用:

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

相关问题