-
Switch Statement Help
Code:
#include <iostream>
using namespace std;
int main()
{
char num;
cout << "Type in the interger you wish to convert: ";
cin >> num;
switch(num)
{
case '1' : cout << "one" << endl;
case '2' : cout << "two" << endl;
case '3' : cout << "three" << endl;
case '4' : cout << "four" << endl;
case '5' : cout << "five" << endl;
case '6' : cout << "six" << endl;
case '7' : cout << "seven" << endl;
case '8' : cout << "eight" << endl;
case '9' : cout << "nine" << endl;
case '10': cout << "ten" << endl;
return 0;
}
}
Keeps producing the errors
Assignment1.cpp:23:6: warning: multi-character character constant
Assignment1.cpp: In function 'int main()':
Assignment1.cpp:23: warning: overflow in implicit constant conversion
any hints/help with this? im still brand new to c++ and am working through a book.
-
A couple of issues here:- num is defined as a char, which can only hold one char info; so 10 would be stored as 1.
- Since you do not break out of your switch statements, everything past the entry point will be printed.
- Your indentation needs dramatic improvement, which would have lead you to see that your return statement is inside of your switch statement.
Something like this is what I believe you are looking for:
Code:
#include <iostream>
int main(void){
int num;
std::cout<<"Enter number:";
std::cin>>num;
switch(num){
case 1:
std::cout<<"One";
break;
case 2:
std::cout<<"Two";
break;
default:
std::cout<<"Not sure";
}
return (0);
}
You can find out more information about the switch statement with Lesson 5: Switch case
-
I haven't used switch-case statements in a while (because my classes decided to drag me through C and assembly for two semesters), but I'm pretty sure it'd be easier to take your input as an integer, and made cases using said integer.
Also, as AndrewHunter said, put break statements in there, and practice indentation. Indenting makes your code a lot more readable, especially as your programs get larger.