简体   繁体   English

尝试将匹配的char变量打印到cout

[英]Trying to print out a matching char variable to cout

So I'm trying to make a coca cola machine to print out what the user has chosen to drink. 所以我正在尝试制作一个可口可乐机器来打印出用户选择饮用的东西。 Basically, I wan't to the user to input a word like "cocacola" as a string, then I convert that into a char type and use that with a if statement. 基本上,我不想让用户输入像“cocacola”这样的单词作为字符串,然后我将其转换为char类型并使用if语句。

But when I run my code it doesn't work. 但是,当我运行我的代码时,它不起作用。

#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 ;

} }

edit : I accidently put switch statement instead of (if). 编辑:我意外地把switch语句而不是(if)。

The reason it is not working is because there is no overload for the == operator for char arrays. 它无法工作的原因是因为char数组的==运算符没有重载。 You want to use strcmp rather than the == operator (actually you should be using strings since this is c++ anyways...). 你想使用strcmp而不是==运算符(实际上你应该使用字符串,因为这是c ++无论如何......)。

#include <cstring>

...

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

If you want to do this with strictly c++. 如果你想用严格的c ++来做这件事。 Then remove the char array sum and instead do 然后删除char数组sum ,而不是

getline(cin, choice);

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

Try modifying your code with this : 尝试使用以下代码修改代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM