Skipping if statement

Look I am actually doing my homework for once, ok can someone explain why this if statement is going allll the way down to the else? I don't know what I am doing wrong here, besides working at 12:50 am.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
	const int SIZE = 20;
	char iceCream[SIZE];
	cout << "What flavor of ice cream do you like best? ";
	cout << "Chocolate, Vanilla, or Pralines and Pecan? ";
	cin.getline(iceCream, SIZE);
	cout << "Here is the number of fat grams for a half ";
	cout << "cup serving:\n";
	if (iceCream == "Chocolate" || iceCream == "chocolate")
	{
		cout << "Chocolate: 9 fat grams.\n";
	}
	else if (iceCream == "Vanilla" || iceCream == "vanilla")
	{
		cout << "Vanilla: 10 fat grams.\n";
	}
	else if (iceCream == "Pralines and Pecan" || iceCream == "Pralines & Pecan")
	{
		cout << "Pralines and Pecan: 14 fat grams.\n";
	}
	else
	{
		cout << "That's not one of our flavors!!!\n";
	}
	return 0;
}
well, your 'iceCream' is a pointer. What you're actually doing is comparing one pointer to another different pointer (and not the content). Use strcmp() to compare the contents
You can't use == when comparing char arrays. What you're really doing is comparing pointers (which will never match unless you're comparing one char array to itself)

The solution here would be to either use strings instead of char arrays:

1
2
3
4
5
6
7
8
9
10
#include <string>

//...

string iceCream;
//...
getline(cin,iceCream);

//...
if(iceCream == "Chocolate" || iceCream == "chocolate") // now this will work 


Or, if you must use char arrays for whatever reason (blech!), you must use strcmp instead of the == operator:

1
2
3
//if (iceCream == "Chocolate" || iceCream == "chocolate")  // no good with char arrays

if( !strcmp(iceCream,"Chocolate") || !strcmp(iceCream,"chocolate") ) // works with char arrays 



EDIT: doh, too slow
Last edited on
It's because iceCream in a char array. In order to use == you have to use strings.

EDIT: WOW! Really should update the screen more I guess.
Last edited on
alright cool! Thanks, I wasn't using strings because of my teacher, but now I know why this is thingy is not working!!
Topic archived. No new replies allowed.