【发布时间】:2021-03-14 19:56:43
【问题描述】:
所以我最近在看一个关于字符串流的教程,并且有一个代码可以进行“数据验证”
std::cout << "\n--- Data validation ------------------------------------" << std::endl;
int value{};
std::string entry {};
bool done = false;
do {
std::cout << "Please enter an integer: ";
std::cin >> entry;
std::istringstream validator {entry};
if (validator >> value)
done = true;
else
std::cout << "Sorry, that's not an integer" << std::endl;
// discards the input buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
} while (!done);
std::cout << "You entered the integer: " << value << std::endl;
std::cout << std::endl;
他说 std::cin.ignore(std::numeric_limits<:streamsize>::max(),'\n') 的原因是忽略一切在流中直到新行,然后我复制了整个代码并从中删除了该行代码并运行它,输入他在测试运行中所做的相同数据(10(ok),frank(失败),.45 (失败),10 frank(ok)),它的工作方式相同,完全没有问题,所以我的问题是为什么它没有改变任何东西以及在什么情况下我可能需要使用 std::cin.ignore (std::numeric_limitsstd::streamsize::max(),'\n')?
【问题讨论】:
-
只是我还是本教程忘记使用
std::cin.clear()清除失败时的cin状态位? -
@Casey
cin如果提供了任何输入,则不应失败,因为它只读取字符串。 -
@IlCapitano 啊。我忽略了那部分。
istringstream也会在每次迭代时重新创建。
标签: c++