C ++字符串和If语句

时间:2019-03-03 03:06:16

标签: c++

目标是要求2种颜色,然后输出适当的辅助颜色(紫色,绿色,橙色),但出现错误,告诉我不能将标准字符串转换为短裤。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
    short result,col_1,col_2,blue,red,yellow;

    const string str1="Purple.",
    str2="Orange.",
    str3="Green.",
    str4="Incorrect, please re-enter.";

    cout<<"Please enter only 2 of the following colors (yellow,blue,red): ";
    cin>>col_1>>col_2;


    if((col_1==red||blue)&&(col_2==red||blue))
    {result=str1;
    }else{
    result=str4;
}
    if((col_1==red||yellow)&&(col_2==red||yellow))
    {result=str2;
    }else{
    result=str4;
}
    if((col_1==yellow||blue)&&(col_2==yellow||blue))
    {result=str3;
    }else{
    result=str4;
}
    cout<<"Your combined color is: "<<result<<endl;
    //for example red and blue should output : Purple.
    return 0;
}

3 个答案:

答案 0 :(得分:1)

您看到的错误消息描述了问题:

short result;
const string str1="Purple.";

[...]

result=str1;

resultshort,而str1std::string。 C ++没有将std::string转换为short的内置方法,因此当您尝试进行分配时,编译器会生成该错误。

也许您是想将result声明为字符串?

答案 1 :(得分:0)

short是数字类型,您的resultshort,但是您的str1str2str3str4string,在C ++中,没有内置的方法可以将string转换为short(或任何转换为​​数字数据类型)。根据您的情况,可以将result声明为字符串。 并且不必将字符串转换为数字!

答案 2 :(得分:0)

即使您“修复”了有关数据类型(短型和字符串型)的错误,您的算法也不是完全正确的,并且无法正确解决问题。 以这些代码行为例:

    if((col_1==red||blue)&&(col_2==red||blue))
    {result=str1; // which is "purple"
    }else{
    result=str4;
}

或者,可能是重写的:

if ((col_1 == "red" || col_1 == "blue") && (col_2 == "red" || col_2 == "blue"))
{
    result = "purple";
}
else
{
    result = str4;
} 

如果col_1 = "red"col_2 = "red"怎么办?根据此代码,结果将为purple(这是意外的)。您应该对其进行一些修改:

if ((col_1 == "red" && col_2 == "blue") || (col_1 == "blue" && col_2 == "red"))
{
    result = "purple"
}
else
{
    result = str4
}

那么,您可以从我重写的代码中学到什么?

  1. 仔细考虑您的算法。在进行编码之前,请确保它是正确的。

  2. 查找有关if语句和数据类型的更多信息。您基本上不能比较或将整数(或short)分配给字符串。

  3. 了解有关如何声明变量的更多信息:仅使用适当的数据类型声明所需的内容。您要输出“颜色”或理论上的字符串,因此结果变量也应该是字符串。 由于您只能将字符串与字符串进行比较,因此,如果要将col_1(或col_2)与另一种颜色(redblueyellow ),这些颜色也必须声明为字符串。声明一个short变量名red并将其与一个字符串进行比较是没有意义的,因为您正在将一个未分配的整数与一个字符串进行比较。正确的方法是,您不需要任何新变量来“存储”此信息,只需将要比较的字符串放在双引号中,或定义这样的变量即可:

    string red = "red"

(我认为这完全没有必要,但无论如何)

  1. 请确保所有输入均使用小写字母,否则必须处理“ REd”和“ reD”之类的东西都等于颜色“ red”。比较之前,您可以比较每一种可能的写法“ red”的方法,也可以将所有单词都转换回小写(或大写)。

  2. 这只是一件小事,但是如果您希望其他人阅读您的代码并为您分析代码,请确保您的代码具有可读性并可能缩进。

这些仅仅是编程的基础,因此您应该更加努力地练习,以免将来遇到这些错误。祝你好运!