C++是一个大小为1但不包含任何内容的字符串

C++ a string which size is 1 but contains nothing

本文关键字:包含任 何内容 字符串 小为 一个 C++      更新时间:2023-10-16

我正在尝试读取一个字符串并使用它来构建bool表达式。

void Parser::parse(){
string temp="";
char c;
for(int i=0;i< _str.length()+1;i++){
    c=_str[i];
    if(c!='~' && c!='=' && c!='|' &&c!='&' && c!=' ' &&c!='>'){
        temp+=c;}
    else if(c==' '){
    }
    else{
        if (temp.substr(0,5)=="false")
            b.add_lit(false);
        else if(temp.substr(0,4)=="true")
            b.add_lit(true);
        else if(temp=="");
        else{
            cout<<"push called"<<endl;
            b.add_var(temp);
        }
        switch (c){
            case '~':{
                string name=get_next_var(_str,i);
                i=get_next_index(_str,i);
                cout<<"i is"<<i<<endl;
                b.add_var(name);
                b.add_op('~');
                b.addparent();
                temp="";
                break;}
            case '|':{
                char lop=b.get_last_op();
                if(lop=='&'||lop=='>'||lop=='='){
                    b.addparent();}
                b.add_op('|');
                temp="";
                break;}
            case '&':{
                char lop=b.get_last_op();
                if(lop=='>'||lop=='=')
                    b.addparent();
                b.add_op('&');
                temp="";
                break;}
            case '>':{
                char lop=b.get_last_op();
                if(lop=='='){
                    b.addparent();}
                b.add_op('>');
                temp="";
                break;}
            case'=':
                b.add_op('=');
                temp="";
        }
    }
        }
if (temp.substr(0,5)=="false")
    b.add_lit(false);
else if(temp.substr(0,4)=="true")
    b.add_lit(true);
else if(temp=="" ) return;
else if(temp!="" ) {
    cout<<"tail called, size:"<<temp.size()<<endl;
    b.add_var(temp);
}
}

当我试图在循环中断后推送最后一个temp时,我总是得到一个temp,这真的很奇怪。在temp字符串的末尾总是有一些我不知道的东西。

假设我从逻辑上得到一个"",也就是temp="",我的代码会显示temp.size()=1,但当我尝试打印它时,它什么也不打印。

这也是为什么我需要减去temp以获得"true"answers"false"。

string get_next_var(string str,int i){
char c;
string temp="";
i++;
for(i;i< str.length();i++){
    c=str[i];
    if(c!='~' && c!='=' && c!='|' &&c!='&' && c!=' '&&c!='>')
        temp+=c;
    else if(c==' '){
    }
    else
        break;
}
return temp;
}
int get_next_index(string str,int i){
char c;
string temp="";
i++;
for(i;i< str.length();i++){
    c=str[i];
    if(c!='~' && c!='=' && c!='|' &&c!='&' && c!=' '&&c!='>')
        temp+=c;
    else if(c==' '){
    }
    else
        break;
}
return i-1;
}

在temp字符串的末尾总是有一些我不知道的东西。

我只是快速浏览了一下你的代码,但我猜这一行是错的:

for(int i=0;i< _str.length()+1;i++) {
    .....
}

我怀疑这就是你想要的:

for(int i=0;i< _str.length();i++) {
    .....
}

这就是为什么:

// Given this
string _str="abc";
// then this is what you will have
_str.length() // 3
_str[0]       // 'a'
_str[1]       // 'b'
_str[2]       // 'c'