C++ - cin 垃圾邮件终端

标签 c++

我正在尝试通过 cin 在 C++ 中获取整数输入,当我尝试这样做时:

int port = 0;

do
{
  std::cout << "Enter port for server: ";
  std::cin >> port;
} while (port <= 0);

如果我没有输入有效的整数,它就会用“输入服务器端口:”向我的终端发送垃圾邮件。我该如何处理这种情况,为什么我的终端会收到垃圾邮件?

最佳答案

您没有验证输入。理想情况下,您应该做的是将输入作为字符串,然后执行转换为您想要的类型。如果你确实想把它们作为整数,你可以在用户输入后检查 cin 的值。如果输入无效,则设置 cin 中的 failbit。

int main(){
    int port = 0;

    do
    {
        std::cout << "Enter port for server: ";
        if(!(cin >> port)){//error occurred
            std::cout << "invalid input" << std::endl;
            cin.clear();//Clear the error
            break;
        }
    } while (port <= 0);

}

关于C++ - cin 垃圾邮件终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553634/

相关文章:

c++ - Stringstream 在一行中双输出最后一个字符串?

c++ - 数组还是 vector ?

c++ - 当从 html 文件中读取 Unicode 内容时,为什么 Unicode 字体无法在 QTextBrowser 中正确显示?

c++ - 如何将 pretty-print 集成为 bazel 构建的一部分

c++ - 使用 libzip 从 .zip 获取文件(文本除外)

c++ - 将外部库中的定义隐藏到我的代码中

c++ - 大规模递归函数中的段错误

c++ - 通过引用 v. 通过指针传递——优点?

c++ - 广度优先搜索输入

c++ - 如何将 RSA 公钥和私钥读入单个 RSA 结构?