首页 > 解决方案 > 检测要在 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。我还想知道这个函数是否可以“堆叠”,比如如果我可以有多个空格和多个单词。

标签: c++whitespace

解决方案


您可以使用std::find_ifstd::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);
}

推荐阅读