2017-04-19 106 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