我有一个函数'int nextCharType(string s)',它应该根据char的“type”返回一个int。
我将按一些自定义类型排序:
我的功能如下:
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;
}
现在我的问题:
我有一些单元测试,其中一个失败,我不知道为什么。 我打电话给
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
有人可以帮忙吗?
答案 0 :(得分:0)
解决方案是存在一个重载函数isValidNumber(double),当给出一个char时,它被调用,而不是isValidNumber(string)。 删除后添加一个新功能:
bool isValidNumber(char c) {
return std::isdigit(c);
}
问题解决了。
答案 1 :(得分:-4)
有许多变量没有声明!所以先声明
&#34;否则如果(((c ==&#39; - &#39; || c ==&#39;。&#39;)&amp;&amp;(i + 1&lt; = s.length()&amp;&amp;&amp;&amp; isValidNumber(s.at(i + 1))))&#34;缺少&#39;)&#39;一个支架!!