const char和二元运算符错误

时间:2013-04-23 19:33:14

标签: c++ string operator-keyword operand

首先要做的事情:我知道这段代码过长,可能会缩短很多。但是,我不想要如何缩短它的帮助,我只是想了解一些基础知识,我现在的问题是运算符和存储值。正如您可以从代码中看到的那样,我试图使用一堆if语句在变量中存储特定值,然后在结尾处将这些值一起显示在字符串中。编译器不喜欢我的代码,并且给了我一堆与运算符相关的错误。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string type = "";
    string color = "";
    string invTypeCode = "";
    string invColorCode = "";
    string fullCode = "";

    cout << "Use this program to determine inventory code of furniture.";
    cout << "Enter type of furniture: ";
    cin >> type;

    if (type.length() == 1)
    {
        if (type == "1" or "2")
        {
         if (type == "1")
         { 
              invTypeCode = "T47" << endl;
              }
         if (type == "2")
         { 
              invTypeCode = "C47" << endl;
              }
              else 
              cout << "Invalid inventory code." << endl;
    }}

    else
         cout << "Invalid inventory code." << endl;

    cout << "Enter color code of furniture: ";
    cin >> color;

    if (color.length() == 1)
    {
        if (color == "1" or "2" or "3")
        {
         if (color == "1")
         { 
              invColorCode = "41" << endl;
              }
         if (type == "2")
         { 
              invColorCode = "25" << endl;
              }
         if (type == "3")
         { 
              invColorCode = "30" << endl;
              }
              else 
              cout << "Invalid inventory code." << endl;
    }}

    else
         cout << "Invalid inventory code." << endl;

    fullCode = invTypeCode + invColorCode;
    cout << fullcode << endl;

    system("pause"); 
    return 0;
}

3 个答案:

答案 0 :(得分:5)

if (color == "1" or "2" or "3")

应该是

if (color == "1" or color == "2" or color == "3")

或者如果您更喜欢正常的风格,那么

if (color == "1" || color == "2" || color == "3")

运营商||or是相同的,但||是旧版本,因此它是大多数人使用的版本。

答案 1 :(得分:3)

看起来您没有正确使用输入和输出流。例如:

         invTypeCode = "T47" << endl;

通常情况下,如果您使用的是endl和&lt;&lt ;,则lhs侧为&lt;&lt; operator是一个std :: ostream。在这种情况下,lhs是一个字符串,这就是编译器抱怨的原因。在这种情况下,我认为你真正想要的是将“T47”替换为“T47 \ n”,并删除“&lt;&lt; endl”。

你最后一次提到“fullcode”时,你的情况也出错了;它需要是“fullCode”,大写“C”。 C ++区分大小写。

答案 2 :(得分:1)

此外,像这样的陈述不会起作用:

         invColorCode = "25" << endl;

不确定您使用endl尝试完成的任务。

相关问题