有没有一种简单的方法可以检查cin输入是否有空格

Is there a simple way to check if cin input has a space?

本文关键字:cin 检查 输入 是否 空格 方法 一种 简单 有没有      更新时间:2023-10-16

假设我有这样的int scin >> s。有没有一种简单的方法可以测试"s"的用户输入是否为空白,而无需求助于isspace,这将导致首先将该int转换为字符串,然后在测试后再次转换为int。

使用std::getline函数将输入的整行作为std::string,然后解析该行,这可以像在C++11:中使用std::stoi一样简单

std::string input;
std::getline(input, input, std::cin);
int const s = std::stoi(input);

它将检查输入的有效性,如果无法执行转换,则抛出异常。此外,输入作为std::string可用,您可以执行任何您喜欢的检查,并且检查字符串中是否存在特定字符是很简单的。

如果你这样做:-

int s;
cin >> s;

它甚至在输入空白时都不会返回。用户必须输入一些非空白字符。