2017-04-19 104 views
-2

制作一个程序,允许用户输入输入,以便他们可以获得简单的数学科目的帮助。我以为我已经做到了,所以如果他们进入了一个不在那里的话题,那么下面的else语句就不会看到这个话题。任何想法为什么当我运行它时,它仍然包括else语句当输入主题是正确的? http://prntscr.com/ey3qyhC++忽略其他语句

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; 
} 
+0

将'search =“square”;'以及之后的所有内容放到'case 2:'中放入else语句中。然后,如果找不到三角形,它只会查找一个正方形。 –

+0

有比正方形或三角形更多的选项,我只是不想包含太多的代码。我会在每个搜索如三角形和正方形之后放入else语句,并且如上所述进行操作吗? –

+0

如果您可以更改它,以便if中的所有代码位于if语句中(例如'search =“square”; pos = sentence.find(search); if(pos!= string :: npos)'into 'if(sentence.find(“square”)!= string :: npos)'),那么你可以将第一个if语句之后的所有if语句改成else if语句。如果不是那么每个如果将不得不在其他内部。我会写一个答案 –

回答

0

您至少有两种选择:

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语句代码,你可以使用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; 
} 

你使用哪一个取决于你是否能适合所有的代码,如果病情我nto条件本身。

+0

非常感谢!我去了第一个选项。 :) –

2

这是你的程序在做什么:

  • 中查找 “三角形”
  • 如果 “三角” 中发现,打印一个三角形的定义。
  • 查找“square”
  • 如果找到“square”,则打印正方形的定义。否则,打印道歉。

由于找到“三角形”并且找不到“方形”,因此会打印三角形的定义和道歉。换句话说,电脑正在按照你所说的去做 - 这是什么问题?

+0

哦,好的。这不是它打算如何哈哈。 我将如何改变它,以便它搜索三角形和只有三角形?如果存储了定义,则会提供该定义,如果不存在,则允许用户再次搜索圆圈以便说出来? –

+0

@ j.doe通过编写一个能够完成这个任务的程序...您希望程序的外观取决于您。 – immibis