我不太喜欢编程,事实上我已经开始并给自己做了一个功课,随便说我是一个菜鸟。
这是问题陈述:
你可以种下两粒种子中的一种(蓝色或红色) 当种植在土壤温度高于75度时,红色会长成一朵花,否则,它会长成一个蘑菇,假设温度满足种植花卉的种植,在湿土壤中种植红色种子会产生向日葵并种植红色种子在干燥的土壤中会产生dandiliom。 在土壤温度下,蓝色的种子会在花中肆虐。从60-70华氏度。或者它是一个蘑菇。在潮湿的土壤中,它是干燥的蒲公英
以下是代码:
*
#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;
}
* 问题是该程序拒绝进入if(soilTemperature&lt; 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();
读取温度后,您在标准输入中有此行结束。然后,您在以下getline中读取emptly行。当然,你错了,程序进入第二个语句,但getline直接用空行完成。
答案 1 :(得分:3)
将[{1}}和std::getline
混合使用以从operator>>
读取时,这是一个常见问题。在消费输入和跳过空格时,std::cin
具有一定的细微差别。
虽然可以正确地做到这一点,但最好避免一开始就处理这种头痛。
将用operator>>
读取温度的代码替换为字符串,就像所有其他代码一样。从中构建一个单独的std::getline
,并使用std::istringstream
上的operator>>
来解析温度。问题解决了。