0

首先要做的事情:我知道这段代码太长了,可以缩短很多。但是,我不想帮助如何缩短它,我只是想了解一些基础知识,而我现在的问题是运算符和存储值。正如您可能从代码中看到的那样,我正在尝试使用一堆 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;
}
4

3 回答 3

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是相同的,但是||是旧版本,所以它是大多数人使用的那个。

于 2013-04-23T19:35:37.977 回答
3

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

         invTypeCode = "T47" << endl;

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

您在最后一次引用“fullcode”时也弄错了案例;它必须是“fullCode”,大写“C”。C++ 区分大小写。

于 2013-04-23T19:41:58.413 回答
1

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

         invColorCode = "25" << endl;

不太确定您要使用endl.

于 2013-04-23T19:37:52.320 回答