微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

string.compare函数未比较正确的字符串

如何解决string.compare函数未比较正确的字符串

不确定为什么,但是当我在代码中使用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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。