通过搜索下一个字符来出乎意料的行为
Unexpected behaviour by searching for next char
我有一个函数'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))))"缺少')'一个括号!
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 通过搜索下一个字符来出乎意料的行为