问题描述
不确定为什么,但是当我在代码中使用string::compare()
时,它将打印相反的switch语句,而不是应该的语句。
cout<<lexeme << " ";
if(lexeme.compare("begin")){
item = LexItem(BEGIN,"begin",linenum);
return item;
}
if(lexeme.compare("print")){
item = LexItem(PRINT,"print",linenum);
return item;
}
在开始比较之前,我cout
是字符串,即使它打印正确的字符串,它也会返回"print"
比较而不是"begin"
:
begin PRINT print 1
有人遇到这个问题,还是知道为什么会这样做?
解决方法
std::string::compare()
返回一个int
,其值为:
如果
*this
以字典顺序出现在参数指定的字符序列之前为负如果两个字符序列都比较相等则为零
正值,如果
*this
出现在参数指定的字符序列之后,按字典顺序
您没有正确计算该返回值。您期望compare()
返回一个布尔值,但不会。
当lexeme
为"begin"
时,lexeme.compare("begin")
返回0,而lexeme.compare("print")
返回< 0
。
在布尔上下文(如if
语句)中,非零整数将被视为true
,而零整数将被视为false
。这就是为什么要获得所看到的输出的原因。
cout << lexeme << " ";
if (lexeme.compare("begin")){ // 0 => false
item = LexItem(BEGIN,"begin",linenum);
return item;
}
if (lexeme.compare("print")){ // < 0 => true
item = LexItem(PRINT,"print",linenum);
return item;
}
尝试以下方法:
cout << lexeme << " ";
if (lexeme.compare("begin") == 0){
item = LexItem(BEGIN,linenum);
return item;
}
if (lexeme.compare("print") == 0){
item = LexItem(PRINT,linenum);
return item;
}
话虽这么说,std::string
实现了比较operator==
,但您应该使用它,例如:
cout << lexeme << " ";
if (lexeme == "begin"){
item = LexItem(BEGIN,linenum);
return item;
}
if (lexeme == "print"){
item = LexItem(PRINT,linenum);
return item;
}