C++忽略else语句

C++ ignoring else statement

制作一个允许用户输入的程序,以便他们可以获得有关简单数学科目的帮助。我以为我已经做到了,所以如果他们输入了一个不存在的主题,它会说下面的 else 语句(不)看到。知道为什么当我 运行 它时,当输入主题正确时它仍然包含 else 语句吗? http://prntscr.com/ey3qyh

search = "triangle";

pos = sentence.find(search);
if (pos != string::npos)
    // source http://www.mathopenref.com/triangle.html
    cout << "A closed figure consisting of three line segments linked end-to-end. A 3 - sided polygon." << endl;

search = "square";
pos = sentence.find(search);
if (pos != string::npos)
    // source http://www.mathopenref.com/square.html
    cout << "A 4-sided regular polygon with all sides equal and all internal angles 90°" << endl;

else
    cout << "Sorry, it seems I have no information on this topic." << endl;

case 2:
    break;
default:
    cout << "Invalid input" << endl;
}

这是您的程序的作用:

  • 寻找 "triangle"
  • 如果找到 "triangle",打印三角形的定义。
  • 寻找 "square"
  • 如果找到 "square",打印正方形的定义。否则,打印道歉。

由于找到了"triangle"而没有找到"square",所以打印三角形的定义和道歉。换句话说,计算机完全按照您的指示执行 - 问题是什么?

您至少有两个选择:

嵌套选项,以便仅在前一个选项不起作用时才评估每个后续选项:

search = "triangle";
pos = sentence.find(search);
if (pos != string::npos){
    // link to info about triangle
    cout << "...info about triangle..." << endl;
}else{
    search = "square";
    pos = sentence.find(search);
    if (pos != string::npos){
        // link to info about square
        cout << "...info about square..." << endl;
    }else{
        search = "pentagon";
        pos = sentence.find(search);
        if (pos != string::npos){
            // link to info about pentagon
            cout << "...info about pentagon..." << endl;
        }else{
            cout << "Sorry, it seems I have no information on this topic." << endl;
        }
    }
}

或者,如果您可以将 if 条件的所有代码放入 if 语句中,您可以使用 else if 语句:

if (sentence.find("triangle") != string::npos){
    // link to info about triangle
    cout << "...info about triangle..." << endl;
}else if (sentence.find("square") != string::npos){
    // link to info about square
    cout << "...info about square..." << endl;
}else if (sentence.find("pentagon") != string::npos){
    // link to info about pentagon
    cout << "...info about pentagon..." << endl;
}else{
    cout << "Sorry, it seems I have no information on this topic." << endl;
}

您使用哪一个取决于您是否可以将 if 条件的所有代码放入条件本身。