[英]Trying to print out a matching char variable to cout
所以我正在尝试制作一个可口可乐机器来打印出用户选择饮用的东西。 基本上,我不想让用户输入像“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)。
它无法工作的原因是因为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 " ;
}
尝试使用以下代码修改代码:
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 " ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.