通过搜索下一个字符来出乎意料的行为

Unexpected behaviour by searching for next char

本文关键字:出乎意料 字符 搜索 下一个      更新时间:2023-10-16

我有一个函数'int nextchartype(string s)',该'应该根据char的"类型"返回int。

我将按几种自定义类型进行排序:

  • array(搜索'[')
  • json(搜索'{')
  • 引号(搜索''')
  • 数字(请参阅Isvalidnumber)

我的功能如下:

int nextCharType(const std::string& s)
{
    char f;
    bool e;
    return nextCharType(s, f, e);
}
int nextCharType(const std::string& s, char& foundChar, bool& error) 
{
    const char errorChar = 0x01;
    const char jsonOpeningBracket = '{';
    const char arrayOpeningBracket = '[';
    const char quoteChar = '"';
    foundChar = errorChar;
    error = false;
    if(s.length() == 0)
    {
        error = true;
        return 0;
    }
    bool foundNumeric = false;
    for(int i = 0; i < s.length() && i != s.npos; i++)
    {
        char c = s.at(i);
        if(c == '')
        {
            i++;
            continue;
        }
        if(c == arrayOpeningBracket || c == quoteChar || c == jsonOpeningBracket)
        {
            foundChar = c;
            break;
        }
        else if(((c == '-' || c == '.') && (i + 1 <= s.length() && isValidNumber(s.at(i + 1))))
            || /*number*/ isValidNumber(c)) // check for sign and decimal char
        {
            foundChar = c;
            foundNumeric = true;
            break;
        }
    }
    if(foundChar == errorChar)
    {
        error = true;
        return 0;
    }
    if(foundNumeric)
        return 4;
    switch(foundChar)
    {
        case jsonOpeningBracket:
            return 1;
            break;
        case arrayOpeningBracket:
            return 2;
            break;
        case quoteChar:
            return 3;
            break;
        default:
            error = true;
            return 0;
            break;
    }
}
bool isValidNumber(const string& num)
{
    if(num.empty())
        return false;
    if(countChar(num, '.') > 1) // countChar will simply count the given char in the string and return an int
        return false;
    if(countChar(num, '-') > 1)
        return false;
    std::size_t pos = 0;
    if(num.at(0) == '-')
    {
        pos = 1;
    }
    string internalNum = num;
    if(internalNum.find_first_not_of("0123456789.", pos) == internalNum.npos)
        return true;
    else
        return false;
}

现在我的问题:

我有一些Unitests,其中一个正在失败,我不知道为什么。我打电话

string s = "  dasdas  {";
// should return 1 for the curly bracket.
int ret = nextCharType(s);
// ret is 4 - numeric value.
// foundChar is ' ' - a space.

让我感到困惑的是,我测试了Isvalidnumber与某些单位测试,如果我对其进行测试,则可以像预期的那样工作。

bool valid = isValidNumber(" "); // space - not valid

有人可以帮助吗?

解决方案是存在一个超载函数isValidnumber(double),当给出一个char时,该函数被称为,而不是Isvalidnumber(string)。将其删除后,添加了一个新功能:

bool isValidNumber(char c) {
    return std::isdigit(c);
}

问题解决了。

  • 在此范围中没有声明" arrayopeningbracket"!
  • 在此范围中没有声明'Foquechar'!
  • 在此范围中没有声明'jsonopeningbracket'!

没有声明许多变量!因此首先宣布

" else if((((((c ==' - '|| c =='。'。i 1))))"缺少')'一个括号!