我正在尝试为多个 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::istringstream
或 boost::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/