所以我正在尝试制作一个可口可乐机器来打印出用户选择饮用的东西。 基本上,我不想让用户输入像“cocacola”这样的单词作为字符串,然后我将其转换为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语句改为(if)。
答案 0 :(得分:2)
它不起作用的原因是因为char数组的==
运算符没有重载。你想使用strcmp而不是==
运算符(实际上你应该使用字符串,因为这是c ++总是......)。
#include <cstring>
...
if(strcmp(sum, "CocaCola") == 0 || strcmp(sum, "cocacola") == 0)
{
cout << "you've chosen CocaCola " ;
}
如果你想用严格的c ++来做这件事。然后删除char数组sum
,而不是
getline(cin, choice);
if( choice == "CocaCola" || choice == "cocacola" )
{
cout << "you've chosen CocaCola " ;
}
答案 1 :(得分: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 " ;
}