2013-04-23 109 views
0

首先要做的事情是:我知道這段代碼太長了,可能會縮短很多。然而,我不想要如何縮短它的幫助,我只是想了解一些基本知識,而我現在的問題是運營商和存儲價值。正如你可能從代碼中看到的那樣,我試圖使用一堆if語句將特定值存儲在變量中,然後將這些值一起顯示在一個字符串中。編譯器不喜歡我的代碼,並給我一堆操作員相關的錯誤。const char和二元運算符錯誤

#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; 
} 
+0

寫入類型==「1」||鍵入==「2」而不是類型==「1」或「2」等。 – Aleph 2013-04-23 19:36:21

+0

研究使用帶有字符串的'operator <<'的std :: stringstream'。 – 2013-04-23 19:53:31

回答

3

它看起來像你沒有正確使用輸入和輸出流。例如:

  invTypeCode = "T47" << endl; 

通常情況下,如果你正在使用ENDL和< <,在LHS端爲< <運算符是一個的std :: ostream的。在這種情況下,lhs是一個字符串,這就是編譯器抱怨的原因。在這種情況下,我認爲您真正想要的是將「T47」替換爲「T47 \ n」,並刪除「endl」中的「< <」。

你在最後一次引用「fullcode」時也遇到了錯誤;它需要是「fullCode」,大寫字母「C」。 C++區分大小寫。

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

而且,像這樣的語句將無法正常工作:

  invColorCode = "25" << endl; 

不能確定你想與endl完成的任務。

相關問題