如何在 if/else 语句中组合字符串C++

How do I combine strings in an if/else statements in C++?

本文关键字:组合 字符串 C++ 语句 else if      更新时间:2023-10-16

我是一个初学者学习C++,我对我在这里出错的地方感到困惑。到目前为止,我有下面的内容,但它没有识别 && 操作数。我会用什么来代替 &&?

我应该做的是编写一个程序,提示用户输入要混合的两种原色的名称。我将不胜感激任何和所有的建议。

谢谢。

 #include <iostream>
    #include <string>
    #include <iomanip>
    using namespace std;
    int main()
    {
        //Declare string variables for colors to mix
        string color;
        string color2;
        string red;
        string yellow;
        string blue; 
        //Output instructions for creating secondary color
        cout<< " Enter first primary color to help create a secondary color.";
        cout<< " Must be in lowercase letters. "<<endl;
        cin>>color;
        cout<< "Enter another primary color to help create a secondary color: ";
        cout<< " Must be in lowercase letters. "<<endl;
        cin>>color2;

        //Create statements to help determine the results
        if (red && yellow)
        {cout<< " Your secondary color is Orange! ";
        }
        else if (red && blue) 
        {cout<< " Your secondary color is Purple! ";

        }
        else if (blue && yellow) 
        {cout<< " Your secondary color is Green! ";
        }
        else 
        {cout<< "Input is inaccurate. Please enter a different color. ";

        }

        return 0;
    }
if (red && yellow)

&&询问每一方的评估结果是否为 true,如果是,则自身评估为 true。

这意味着您的代码询问变量red的计算结果是否为 true,变量的计算结果yellow是否为 true。

但那些是字符串!(还有空的!相反,您希望比较输入的字符串,并查看比较的计算结果是否为 true:

if (color1 == "red" && color2 == "yellow")

类似

if (color == "red" && color2 == "yellow")

变量的名称不是字符串。

当运算符的两端都是bool对象或可以转换为bool的对象时,运算符&&有效。因此,这条线

    if (red && yellow)

在语法上不正确。

可以使用以下命令在代码中正确表达您的意图:

    if (color == "red" && color2 == "yellow" )

如果将变量的 vlaues 定义为 redyellow

    string red = "red";
    string yellow = "yellow";

那么您也可以使用:

    if (color == red && color2 == yellow )