有没有一种简单的方法可以检查cin输入是否有空格
Is there a simple way to check if cin input has a space?
假设我有这样的int s
和cin >> 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;
它甚至在输入空白时都不会返回。用户必须输入一些非空白字符。
相关文章:
- 如何检查cin是否与数组中的一组数字匹配
- 我如何检查CIN.FAIL(),但仍使用Ctrl D到达文档的结尾
- C++ 检查 cin 的输入是否正确数据
- 如何检查 cin 缓冲区是否包含相同的值 0.5 秒 (C++)
- C++如何检查std::cin缓冲区是否为空
- C - 检查CIN是否有错误
- if(!getline(std::cin,str1))break;这个条件检查什么
- 如何检查std::cin是否与端子或管道关联
- 检查C++字符串中的整数:已修订:清除 cin
- 检查 cin.fail() 中字符串变量时出错C++
- 检查有效的 CIN 输入时出现问题
- 如何检查 cin 在 c++ 中是否为 int
- 检查 cin 输入流会生成一个整数
- 有没有一种简单的方法可以检查cin输入是否有空格
- 如何检查用户CIN输入是太少还是太多
- 检查cin结果c++
- 使用std::cin (c++)检查有效的类型输入
- Cin读取数字并检查整数
- 使用std::cin对出界char-Array进行错误检查
- 检查输入的值是否为float,清除cin