C++ cout in while 循环打印两次

标签 c++

我改编了 Bjarne Stroustrup 的《编程:C++ 原理与实践》中的这段代码,试图检查给定的输入是否有效:

#include <iostream>
using namespace std;

int main()
{
    cout << "Please enter your first name and age: ";
    string first_name = "???";
    int age = -1;
    cin >> first_name >> age;

    while (!cin) {
        cin.clear();
        cout << "Sorry, can you enter that again? ";
        cin >> first_name >> age;
    }

    cout << "Hello, "<<first_name<<"! (age "<<age<<")\n";
    return 0;
}  

这按预期工作,除了单词 "Sorry, can you enter that again? " 被打印两次,一次在第二次输入之前,一次在第二次输入之后。

有人知道为什么会这样吗?谢谢。

最佳答案

仅仅清除失败位是不够的,您还必须清除输入缓冲区中所有剩余的字符。此外,代码看起来比必要的更复杂。以下作品:

std::string name;
int age;

std::cout << "Please enter your name & age: ";

while (not (std::cin >> name >> age)) {
    std::cout << "Sorry, can you enter that again? ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

std::cout << "Hello " << name << " (" << age << ")\n";

哦,是的,别忘了刷新输出流,我认为这不会自动为您完成。

也就是说,标准输入/输出流是,所以它们并不真正适合交互式输入。您应该为此使用适当的库,例如 readlinencurses

为了说明为什么这很重要,假设用户输入“foo42”并按下回车键。你希望程序现在说“对不起,你能再输入一次吗?”但事实并非如此。相反,它温顺地等待用户输入第二个 token 。从可用性的角度来看,这肯定不是您所期望的。

关于C++ cout in while 循环打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422331/

相关文章:

c++ - 如何将方法作为参数传递?

c++ - 为什么我的代码在 SPOJ 上给出了错误的答案?

c++ - 基于使用 make 命令或 makefile 运行预处理器

c++ - 如何在 C/C++ 中获取多维数组的列?

c++ - gcc 链接器找不到库

c++ - 如何指定 setprecision 舍入

c++ - 将此类传递给引用的正确语法是什么?

c++ - 字符串移动赋值交换值

c++ - 在调用 cmake 之前删除构建文件夹中的所有内容是否合理?

c++ - 类成员函数的基于范围的for循环?