c++ - 检测要在 if 语句中使用的输入空白
问题描述
我正在尝试创建一个 C++ 程序,该程序检测何时将空白输入到cin
一行,然后检测它后面的单词。我只在这里展示我的功能:
int lineFunction (string line) {
if (/*whatever characters, then whitespace, and the letter ‘a’ is read*/) {
return 0;
}else if (/*whatever characters, then whitespace followed by the letter ‘b’*/) {
return 1;
}else {
return 2;
}
}
所以如果输入是,比如说:abc a
那么输出应该是0,如果输入是abc b
那么输出应该是1,否则应该是2。我还想知道这个函数是否可以“堆叠”,比如如果我可以有多个空格和多个单词。
解决方案
您可以使用std::find_if和std::isspace
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int lineFunction(std::string line) {
auto begin = std::find_if(std::begin(line), std::end(line), [](unsigned char c){ return std::isspace(c); });
if (begin == std::end(line) || ++begin == std::end(line)) return 2;
auto end = std::find_if(begin, std::end(line), [](unsigned char c){ return std::isspace(c); });
std::string word(begin, end);
if (word == "a") {
return 0;
} else if (word == "b") {
return 1;
} else {
return 2;
}
}
int main() {
std::string line = "abc a";
std::cout << lineFunction(line);
}
推荐阅读
- haskell - 如果启用了 OverloadedStrings 扩展,则函数长度“a”不会编译
- javascript - Google Analytics:警告:无法对未安装的组件执行 React 状态更新
- javascript - 您将如何使用函数每秒增加一个变量值?
- c# - 我们如何忽略在 RequestResponseLoggingMiddleware AspNetcore3 中写入文件内容
- reactjs - React - 让用户保持在同一页面上 - 防止页面刷新
- ios - 警报弹出框的约束问题
- r - data.table 的 `:=` 操作符真的是通过引用来操作的吗?
- python - Pydantic 的 SecretStr 的目的是什么?
- javascript - Vue.js - 在 b-form-textarea 中未调用侦听器 @oninput.native
- php - 在静态函数中结合多自我