switch statements using int

Oct 26, 2012 at 3:44pm
Hi, I am somewhat new to C++. I am testing switch statements to better understand how they work. I created a simple program, but my program is not functioning the way it should. I don't have any compiling errors, but the program exits right away. I'm not sure if I'm using the switch statements correctly:

int option = 0;

switch(option) {
case = '1':
Input(); //this is part of a class
case = '2':
Display(); //this is part of a class
case = '0':
cout <<"Good Bye" << endl;
break;
}
I want the program to display the functions when the user has entered either 1 or 2 and exit when 0 is entered. Also, is a switch statement similar to if/else? Or is my thought process completely off.
Oct 26, 2012 at 3:49pm
Have you seen the "The selective structure: switch." section on this page?

Control Structures
http://www.cplusplus.com/doc/tutorial/control/

It's includes an example of a switch statement and the equivalent if statement

Andy
Oct 26, 2012 at 3:50pm
Please use code tags

You have a couple of problems here
First have a break after every case unless you know what youre doing
And second dont use ' ' around the numbers. Instead just put
1
2
3
4
5
6
case 1:
//Bla bla bla
break;
case 2:
//etc
break;
Oct 26, 2012 at 3:54pm
What Angeljruiz said,

using the 'break;' keyword will break the loop, otherwise the switch will carry on running. So if you value is 2, and you don't have a break, it will play everything under 2.

Also switch can ony be used with 'char' and 'int', as far as I'm aware.
Oct 26, 2012 at 4:01pm
Thank you andywestken, Angeljruiz andCallum5042,

I took out the single quotes and added the break in. Program is functioning correctly.

Again Thank you,

Ammo
Oct 26, 2012 at 8:13pm
Do you understand why the single quotes were giving you problems, or did you just get the right result and move on?

http://cplusplus.com/doc/tutorial/constants/

'1' is the constant value for the character 1. It has an integer value 49 (in ASCII).
Last edited on Oct 26, 2012 at 8:16pm
Oct 27, 2012 at 6:43am
Yea I realized it after. If I was using char it would have been okay. I realized that single quotes are used for characters and double quotes are used for string.
Topic archived. No new replies allowed.