2013-03-24 88 views
-1
#include <iostream> //include header files 

using namespace std; 

int main() //start of main body 

{ 

int num; //declaring integer 

int control=1; //declaring integer 

while(control==1)//start of loop, as long as condition is true 
{ 
    cout << "Press 1 for coffee" << endl; //writes to standard o/p 
    cout << "Press 2 for tea" << endl; 
    cout << "Press 3 for hot chocolate" << endl; 
    cout << "Press 4 for soft drink" << endl; 
    cout << "Press 5 to exit" << endl; 
    cin >> num; 


if (num == 1) //code to execute if integer = 1 
{ 
    cout << "coffee selected" << endl; 
} 
else if (num == 2) //code to execute integer = 2 
{ 
    cout << "tea selected" << endl; 
} 
else if (num == 3) //code to execute if integer = 3 
{ 
    cout << "hot chocolate selected" << endl; 
} 
else if (num == 4) //code to execute if integer = 4 
{ 
    cout << "soft drink selected" << endl; 
} 
else if (num == 5) //code to execute if integer = 5 
{ 
    cout << "Exit Program" << endl; 
    control=0; 
} 


} 

比較,誤差

是我ammended代碼這個工程。然而,我不確定初始化數字整數,所以我離開它,但代碼仍然執行並正常工作。

+4

'如果(NUM == 1)',** **不'如果(NUM == 「1」)'。 – us2012 2013-03-24 17:10:50

+1

(歡迎使用stackoverflow。請閱讀常見問題解答,並且爲了將來的問題,請記住,如果您(1)做出一個簡短而簡明的例子來展示您的意思,那麼人們將更有可能幫助您 - 您可以削減80%的代碼,仍然顯示問題,並且(2)提供準確的錯誤信息和行號,並在代碼中標記相關行,以便我們不必逐行閱讀。) – us2012 2013-03-24 17:12:46

+4

也可能想要將某些內容實際分配給num '在某個時候。 – JasonD 2013-03-24 17:13:27

回答

2

你在這裏比較整數字符串num == "1"。相反,使用num == 1

3

的錯誤是,你比較的intnum),用字符串文字如"1"。這個特定的字符串文字的類型爲const char[2],其衰減到const char*,因此編譯器錯誤。

你需要用數字來比較數字,例如

if (num == 1) { .... } 
2

您正在嘗試比較字符串文本的數字。 不是一個很好的計劃。嘗試

if(num==1)

if(num=="1")

其次,num是不確定的。嘗試設置一個值。

由於您無法比較兩種不同的數據類型,因此C++編譯器會給您帶來錯誤。有關比較的更多信息here

2

因爲您要求用戶輸入整數,所以您不需要menustring類型。 只需使用

if (num == 1) 

if (num == "1") 
1

整數進行比較與字符串:)

num == "1" 

不允許的,順便說一句,我認爲不是 「民」 你們希望 「菜單」,這是一個字符串?

1

首先,你的num是未初始化的。 時,你會改變這一點,那麼也改變從num == "1"num == 1

比較目前你把你的輸入變量menu當你做getline (cin, menu, '\n');所以你必須要改變這一點,如果你想存儲在num輸入。

這旁邊是非常不錯代碼,我會選擇4)

+0

感謝球員,我已經做了從num ==「1」到num == 1的比較的更改,並取出了字符串,並將輸入存儲在num變量中,我也將else語句放在了原來的位置不需要,但我還沒有初始化的num變量,但代碼仍然執行是這種良好的做法? – user2204993 2013-03-24 18:36:44

+0

@ user2204993請對代碼進行這些更改,以便我們可以看到您已完成的操作以及您現在的問題 – 4pie0 2013-03-24 18:47:51