【问题标题】:How to store one value at a time with cin?如何用cin一次存储一个值?
【发布时间】:2016-05-23 06:13:21
【问题描述】:

我正在尝试为多个 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 将值保留在输入流中有关,但我如何让它一次只接受一个值?

【问题讨论】:

  • 很抱歉我没有使用它,我认为只要看看输出就可以自我解释了。

标签: c++ validation input user-input


【解决方案1】:

使用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');

【讨论】:

  • 感谢@LogicStuff,非常感谢您抽出宝贵时间帮助我。我拿了你的代码并做了一些修改,这部分对我帮助很大else if(iss.rdbuf()-&gt;in_avail() &gt; 0)我不知道我能做到这一点。我正在阅读参考文本以更好地理解这两个功能,但我真的不明白-&gt; 运算符的含义是什么?这是in_avail() 的管道吗?
  • iss.rdbuf() 返回一个指针,这就是您取消引用它并调用其in_avail 函数的方式。 en.cppreference.com/w/cpp/language/operator_member_access
猜你喜欢
  • 2021-05-22
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多