c++ - 程序拒绝进入第二条语句

标签 c++

我不太擅长编程,事实上我已经开始并给自己布置了作业,尽管说我是菜鸟。

这是问题陈述:

你可以种下两种种子中的一种(蓝色或红色) 如果土壤温度高于 75 度,红色会长成花,否则,如果温度满足生长条件,它会长成蘑菇。在潮湿的土壤中种植红色种子会产生向日葵,并种植红色种子在干燥的土壤中会产生蒲公英。 在土壤温度下,蓝色种子会开出花朵。从 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;
}

* 问题是程序拒绝进入 if(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";
        }
    }

蓝色也一样。

最佳答案

读取温度后需要忽略\n:

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

读取温度后,标准输入中有这个行尾。然后,您读取以下 getline 中的空行。当然,你错了,程序进入了第二条语句,但是getline直接以空行结束。

关于c++ - 程序拒绝进入第二条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657195/

相关文章:

c++ - 在程序中捕获 C++0x 标志

c++ - 如何使用 CryptoApi 导入 PKCS#8

c++ - 处理 GetSidIdentifierAuthority 函数的返回值

c++ - CLOCKS_PER_SEC 是否意味着每台计算机会有不同的时间概念?

c++ - QT5 C++,有没有办法我可以在qlist容器中获取小部件的当前文本

c++ - 如何使用包装在 ComPtr 中的 Direct3D 11 指针来获取 11.1 接口(interface)?

c++ - 如何处理 -Wreturn-type 以切换 C++11 枚举类?

c++ - 折叠表达式的结合性

c++ - 表达三元条件的结果类型 `?:`

c++ - 如何编写具有可变数量参数的 Excel 加载项函数(例如 : MAX, MIN ...)