2013-12-19 32 views
1

所以我試圖讓可口可樂機器打印出什麼用戶選擇飲用。 基本上,我wan't用戶輸入如「可口可樂」作爲一個字符串的話,那麼我認爲轉換成char類型和使用,用if語句。試圖打印出匹配的字符變量來清點

但是當我運行我的代碼,這是行不通的。

#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std ; 

int main(){ 

cout << "You approach the Cola Machine..." ; 
cout <<"these are the different drinks it offers." << endl << endl ; 
cout <<"CocaCola\nSquirt\nSprite\nWater\nHorchata" << endl << endl ; 
cout <<"Type in what you would like to drink: " ; 

string choice ; 
char sum[300] ; 


cin >> choice ; 
    strncpy(sum, choice.c_str(), sizeof(sum)); 
    sum[sizeof(sum) - 1] = 0; 

if(choice == choice) { 
if((sum == "CocaCola" || sum == "cocacola")){cout << "you've chosen CocaCola " ;} 
    } 
return 0 ; 

}

編輯:我不小心把代替(如果)switch語句。

+0

有什麼特別的原因C字符串參與呢? – chris

+0

請勿使用strcpy。它的過時,它公司的C – Manu343726

+0

我一直在尋找一種方法,使這項工作,首先我想的static_cast,但沒有運氣,我發現了一個網上論壇,使用的strcpy作爲解決方案。 –

回答

2

它不工作的原因是因爲沒有爲==運營商字符數組沒有超載。你想用strcmp而不是==操作(其實你應該使用字符串,因爲這是C++反正...)。

#include <cstring> 

... 

if(strcmp(sum, "CocaCola") == 0 || strcmp(sum, "cocacola") == 0) 
{ 
    cout << "you've chosen CocaCola " ; 
} 

如果你想用嚴格的C++來做到這一點。然後取出字符數組sum,而是做

getline(cin, choice); 

if(choice == "CocaCola" || choice == "cocacola") 
{ 
    cout << "you've chosen CocaCola " ; 
} 
+0

我只想使用字符串,但是當我使用==運算符時,我得到了常量錯誤在cmd上。我寧願只堅持C++,我只是這樣做來學習,我沒有嚴格的方法來做到這一點。 –

+0

回答只更新了C++解決方案 – smac89

+0

哇,我可能只是有一個語法錯誤或什麼?不知道我怎麼會錯過你的答案的第二部分,無論如何感謝C++的細分市場,併爲c的見解。 –

1

嘗試用這個修改代碼:

strncpy(sum, choice.c_str(), sizeof(sum)); 
sum[sizeof(sum) - 1] = 0; 

string sum_string(sum); 

if((sum_string== "CocaCola") || (sum_string== "cocacola")) 
{ 
    cout << "you've chosen CocaCola " ; 
} 
+0

謝謝,它工作得很好,但我現在只會堅持使用C++。無論如何,我只是在論壇上使用c bc才發現它。 :) –

相關問題