1

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.

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).

Bryan Fajardo
  • 153
  • 2
  • 15

2 Answers2

2

The reason it is not working is because there is no overload for the == operator for char arrays. You want to use strcmp rather than the == operator (actually you should be using strings since this is c++ anyways...).

#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++. Then remove the char array sum and instead do

getline(cin, choice);

if( choice == "CocaCola" || choice == "cocacola" )
{
    cout << "you've chosen CocaCola " ;
}
smac89
  • 26,360
  • 11
  • 91
  • 124
  • I WAS trying to use strings only, but when I used the == operator the I got constant errors on the cmd. I would prefer to stick to c++ only, I'm just doing this to learn there's no strict way for me to do it. – Bryan Fajardo Dec 19 '13 at 06:52
  • WOW,I may have simply had a syntax error or something? Not sure how I could miss the second part of your answer, anyways thanks for the c++ segment, and for the c insight. – Bryan Fajardo Dec 19 '13 at 06:57
1

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 " ;
 }
Biraj Borah
  • 101
  • 8
  • Thank you, it worked good, but I will stick only to c++ at the moment. I was only using c bc I found it on a forum, thanks for the C insight anyhow. :) – Bryan Fajardo Dec 19 '13 at 06:58