2016-07-29 52 views
0

我不是在編程太goood,其實我已經開始和給自己一門功課,隨意說我是個菜鳥。程序拒絕進入第二個語句

這裏的問題陳述:

你可以種兩號種子之一(藍色或紅色) 種植在土壤溫度高於75度時,阿紅將長成一朵花,否則,它會成長爲一個蘑菇假設溫度滿足種植花卉的限制,溼土壤中的紅色種子會產生向日葵,在乾燥的土壤中種植紅色種子會產生d子。 藍色的種子在土壤溫度下會產生花朵。從60-70 F度。或者它的蘑菇。在潮溼的土壤的幹

這裏蒲公英的代碼:

*

#include "stdafx.h" 
#include <iostream> 
#include <string> 
using namespace std; 
int main() 
{ 
    string plantedSeed = ""; 
    string seedColor = ""; 
    cout << "What color will the seed be? (red/blue): \n"; 
    getline(cin, seedColor); 
    int soilTemperature = 0; 
    cout << "What temperature will the soil have?\n"; 
    cin >> soilTemperature; 
    if (seedColor == "red") 
    { 
     if (soilTemperature >= 75) 
      plantedSeed = "mushroom"; 
     if (soilTemperature < 75) 
     { 
      string seedState = ""; 
      cout << "Enter the state of the soil in which the seed is plantet to (wet/dry)\n"; 
      getline(cin, seedState); 
      if (seedState == "wet") 
       plantedSeed = "sunflower"; 
      if (seedState == "dry") 
       plantedSeed = "dandelion"; 
     } 
    } 
    if(seedColor == "blue") 
    { 
     if (soilTemperature >= 60 && soilTemperature <= 70) 
      plantedSeed = "mushroom"; 
     else 
     { 
      string seedState = ""; 
      cout << "Enter the state of the soil in which the seed is plantet to (wet/dry)\n"; 
      getline(cin, seedState); 
      if (seedState == "wet") 
       plantedSeed = "dandelion"; 
      if (seedState == "dry") 
       plantedSeed = "sunflower"; 
     } 
    } 
    cout << "The planted seed has transformed into: " << endl; 
    cout << plantedSeed << endl; 
    system("pause"); 
    return 0; 
} 

* 的問題是程序拒絕進入,如果(soilTemperature < 75)語句

if (seedColor == "red") 
    { 
     if (soilTemperature >= 75) 
      plantedSeed = "mushroom"; 
     if (soilTemperature < 75) 
     { 
      string seedState = ""; 
      cout << "Enter the state of the soil in which the seed is plantet to (wet/dry)\n"; 
      getline(cin, seedState); 
      if (seedState == "wet") 
       plantedSeed = "sunflower"; 
      if (seedState == "dry") 
       plantedSeed = "dandelion"; 
     } 
    } 

它是藍色的一樣。

+0

使用字符串比較功能。 –

回答

4

你需要閱讀的溫度後忽略\n

cout << "What temperature will the soil have?\n"; 
cin >> soilTemperature; 
cin.ignore(); 

讀取溫度後,你有這樣的結束行中輸入STANDAR。然後,您閱讀以下getline中的空白行。當然,你錯了,程序進入第二個語句,但getline直接用空行結束。

+0

非常感謝,你救了一個新手。 – newbProgrammer

3

當混合使用std::getlineoperator>>來讀取std::cin時,這是一個常見問題。當涉及到消費輸入和跳過空白時,operator>>具有一定的細微語義。

雖然可以正確地做到這一點,最好是避免處理這個頭痛擺在首位。

替換讀取與std::getline溫度轉換成字符串,只是像所有其他的代碼。構造從一個單獨的std::istringstream,並使用operator>>std::istringstream解析溫度。問題解決了。

+0

謝謝,但一個簡單的cin.ignore();我救了我,雖然我不知道我現在知道這樣的事情存在。 – newbProgrammer