检查字符串中的所有字符是否为1,0或""

b13*_*3rg -1 c++

我正在尝试创建一个布尔函数,如果字符串只包含1,0和空格,则返回false.否则它返回true到函数调用嵌套的while循环.这是我到目前为止的代码:

bool check_bin_num(string& bin) {
     for (int i = 0; i <= back.length(); i++) {
          if (!(bin[i] == '0' || bin[i] == '1' || bin[i] == ' ')) {
               return true;
          }
     }
     return false;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

5go*_*der 6

这可以用一行写成std::string::find_first_not_of:

s.find_first_not_of("01 ") == std::string::npos
Run Code Online (Sandbox Code Playgroud)

将计算为true当且仅当所述std::string s完全由字符'0','1'' '(空间).