为什么字符串比较失败? 我试图逐行读取C++文件,我已经把每一行读成向量。文件内容如下: 00001010 01101010 10101011 11110111

为什么字符串比较失败? 我试图逐行读取C++文件,我已经把每一行读成向量。文件内容如下: 00001010 01101010 10101011 11110111,c++,string,string-comparison,C++,String,String Comparison,我试图精确地计算以00、01和10开头的行,使用下面的比较可以很好地工作 std::string opcode = GetInstruction().substr(0,2); std::string fucode = GetInstruction().substr(7); if(opcode == "01") { AddInstruction(GetInstruction()); } else if(opcode == "10") {

我试图精确地计算以00、01和10开头的行,使用下面的比较可以很好地工作

    std::string opcode = GetInstruction().substr(0,2);
    std::string fucode = GetInstruction().substr(7);

    if(opcode == "01") {
        AddInstruction(GetInstruction());
    }
    else if(opcode == "10") {
        SubInstruction(GetInstruction());
    }

    else if(opcode == "00") {
        LoadInstruction(GetInstruction());
    }
似乎不起作用的部分是,如果我尝试提取以11开始,以1结束的行。为此,我做了以下比较

    else if((opcode == "11") && (fucode == "1")){
        std::cout<<GetInstruction();
        PrintInstruction(GetInstruction());
    }
else如果((操作码==“11”)&&(fucode==“1”)){

std::cout我知道问题出在哪里,但我不能很好地解释原因。也许其他人可以对此进行扩展。改变

else if((opcode == "11") && (fucode == "1")){
    std::cout<<GetInstruction();
    PrintInstruction(GetInstruction());
}
else如果((操作码==“11”)&&(fucode==“1”)){

std::coutWhat
GetInstruction()
return?它是否每次调用时都返回相同的值?GetInstruction从上面的二进制数序列中返回一行,例如00001010作为字符串。因此,当您调用它两次时,它是否返回两行不同的行?代码片段调用的前两行
GetInstruction()
两次。我想知道
opcode
fucode
是否引用了同一条指令。@DYZ Yes opcode和fucode在当前迭代中引用了同一条指令。fucode是最后一位,而opcode是前两位。它现在可能可以工作了,因为如果字符串相等,并且有一个数字指示不同的值,compare将返回0否则(1/-1)。这可能不是您想要的。事实上,您已经使它有效地等效于
if((操作码!=“11”)&&&(fucode!=“1”)
,所以我应该使它
(!opcode.compare(“11”)&&&&!fucode.compare(“1”)
 else if(opcode.compare("11") && fucode.compare("1")){
    std::cout<<GetInstruction();
    PrintInstruction(GetInstruction());
}