Jan 15, 2012 at 12:20pm UTC
This code, what i made, works in Visual C++ 2005, but doesn't work ir Visual c++ 2008.
Visual C++ 2005 if i enter 1,2,3,4,5, than choose drink.
Visual C++ 2008, only choose default.
Why is it?
#include <iostream>
#include <string>
using namespace std;
int main() {
int x;
cout << "Choose drink" << endl;
cin>>x;
switch(x) {
case '1':
cout << " Coke " << endl;
break;
case '2':
cout << " Cocacola " << endl;
break;
case '3':
cout << " Limonade " << endl;
break;
case '4':
cout << " sprite " << endl;
break;
case '5':
cout << " fanta " << endl;
break;
default:
cout << " You choose nothing. Don't forget your money " << endl;
break;
}
}
Jan 15, 2012 at 12:27pm UTC
Note:
'5' is a character (type
char ). It has the value 53. See ASCII table:
http://www.asciitable.com/
5 is a number (default type
int ). It has the value 5.
Easy solution 1:
1 2 3 4
switch (x) {
case 1: // not '1'
// ...
}
Easy solution 2:
char x; // not "int x;"
Edit: added second solution.
Last edited on Jan 15, 2012 at 12:30pm UTC
Jan 15, 2012 at 12:28pm UTC
Remove the single quotes surrounding the numbers.
Jan 15, 2012 at 12:57pm UTC
What a mistake.
Thank you for help.