std::cin>> 是数字或字符串

kay*_*orr 0 c++ cin stdstring typechecking

我必须确定输入是数字还是字符串。

std::string s;
while (std::cin >> s) { 
    if(isdigit(s)){
        //do something with the variable
    }
    else{
        //do something else with the variable
    }
}
Run Code Online (Sandbox Code Playgroud)

为此,我得到 error: no matching function for call to 'isdigit(std::__cxx11::string&)' 有人可以提出我应该使用的方法吗?

rob*_*oke 7

isdigit()'0'适用于单个字符(并指示它是否是和之间的数值'9')。要检查您是否有单个数字:

std::string s;
while (std::cin >> s) { 
    if(s.size() == 1 && isdigit(s[0])){
        //do something with the variable
    }
    else{
        //do something else with the variable
    }
}
Run Code Online (Sandbox Code Playgroud)

检查所有字符是否都是数字...

std::string s;
while (std::cin >> s) { 
    bool alldigits = true;
    for(auto c : s) {
       alldigits = alldigits && isdigit(c);
    }

    if(alldigits){
        //do something with the variable
    }
    else{
        //do something else with the variable
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在第二种情况下,还可以使用“std::all_of”代替循环。 (2认同)