c++ - 如何用cin一次存储一个值?

标签 c++ validation input user-input

我正在尝试为多个 double 变量赋值,并且我正在使用 std::cin。但如果用户使用空格,它会跳过变量。

应该如何:

Please enter the value for var1: 1 [Space] 2 [Space] 3
Please enter one variable at a time.
Please enter the value for var1: 1 [Enter]
Please enter the value for var2: 2 [Enter]
Please enter the value for var3: 3 [Enter]

You have entered the values, 1, 2 and 3 for var1, var2 and var3.

它现在正在做什么:

Please enter the value for var1: 1 [Space] 2 [Space] 3
Please enter the value for var2:
Please enter the value for var3:

You have entered the values, 1, 2 and 3 for var1, var2 and var3.

我知道这与 std::cin 将值保留在输入流中有关,但如何使其一次只接受一个值?

最佳答案

使用 std::getline 读取整行,然后使用 std::istringstreamboost::lexical_cast 解析该行。 .

std::istringstream 版本类似于(未测试):

std::getline(std::cin, line);
std::istringstream iss(line);
double value;

if(!(iss >> value))
{
    iss.clear();
    // invalid value
}
else if(iss.rdbuf()->in_avail() > 0)
{
    // there are more characters in the stream
}

如果您不想向用户提供任何反馈,您可以这样做(不使用 std::getline):

if(!(std::cin >> value))
{
    std::cin.clear();
    // invalid value
}

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

关于c++ - 如何用cin一次存储一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356783/

相关文章:

c# - 有没有办法让 ValidationSummary 与客户端验证器一起工作?

c - 没有输入时如何在scanf()中检测?

php - Laravel 5.1 中的自定义验证替换器

c++ - 在C++中使用WinUI的指南

c++ - 尝试在 Linux 上使用 Borland header 时出现 undefined reference

c++ - 使用 SFINAE 测试指针类型是否可以静态转换为另一种指针类型

arrays - 类验证器 - 验证对象数组

jquery - 使用 jQuery 即时更新范围值

java - 将 Java 应用程序转变为 Servlet

c++ - 将指向给定子类的指针从一个 vector 复制到另一个 vector