c++ - bool 函数返回意外值

标签 c++

isValid("23:15") 在应该返回 1 时返回 0

bool isValid(string s){
    int pos = s.find(":");
    if(s.length() < 4 || s.length() > 5)
        return false;
    else if(s.length() == 5)
    {
        if(s[0] > 2)
            return false;
    }
    if(s[pos + 1] > 5 )
    {
        return false;
    }
    return true;
}

实际输出= 0

最佳答案

我猜你把数字和数字搞混了。

if(s[0] > 2)

应该是

if (s[0] > '2')

if(s[pos + 1] > 5 )

应该是

if (s[pos + 1] > '5')

您还需要考虑如果 s 不包含冒号会发生什么情况。

关于c++ - bool 函数返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639249/

相关文章:

c++ - 重载 + 运算符以添加 2 个多项式 C++

c++ - Matlab 不会运行我的 C++ .exe 文件

c++ - Com 端口 C++ 读取 0xFF

c++ - 程序计算辅音错误

c++ - 我应该使用 wchar 还是 char 来加密?

c++ - unordered_map 中带有模板类的 C2535(Microsoft Visual Studio 2015 CTP6)

c++ - 运行时错误: Integer Overflow for Complement Number Problem

c++ - 为链表重载 operator+

C++ 运算符重载 - uni 测验答案看起来错误?

c++在使用串口发送之前将十六进制转换为ASCII