Switch problems

Is it possible to use a string as the variable checked in a switch statement?
I want to use it to check the command entered by a user and then call the appropriate function. I suppose an else if setup would work but I'm lazy. :P
No. Only integers.
I recently made a basic program using switch statement wherein the input must be determined if user's input is a vowel or a consonant. here is my code:

#include <iostream.h>
#include <conio.h>
Char fav;
Main()
{
Clrscr()
Cout<< “Write your favorite letter in the alphabet:”;
Cin>>fav;
Cout<<”Let me check if your favorite vowel is a consonant or a vowel.”;
Switch (fav)
{
Case ‘A’ || ‘a’: “Your favorite letter is a vowel. Thank you for using this program.”; break;
Case ‘E’ || ‘e’: “Your favorite letter is a vowel. Thank you for using this program.”; break;
Case ‘I’ || ‘I’: “Your favorite letter is a vowel. Thank you for using this program.”; break;
Case ‘O’ || ‘o’: “Your favorite letter is a vowel. Thank you for using this program.”; break;
Case ‘U’ || ‘u’: “Your favorite letter is a vowel. Thank you for using this program.”; break;
Default: “Your favorite letter is a consonant. Thank you for using this program.”; break;
}
Getch();
Return 0;
}


My problem is what if the user input a number, it will still be deemed as consonant because of the default statement right? How would i know if the user's input is a character and not an integer? Can I present that case as : Case !sizeof (char): “You did not provide a letter. Thank you for using this program.”; break;?
Whoa whoa WHOA!

C++ is a case-sensitive language. De-capitalize all instances of "Char", "Main", "Clrscr", "Cout", "Cin", "Switch", "Case", "Default", "Getch", and "Return".

And... switches do not work quite like ifs.
http://cplusplus.com/doc/tutorial/control/
Scroll down to the bottom.

And... in the future, could you make a separate thread? Thanks. ;)

-Albatross
Last edited on
you can use the insertion operator to test. It's a little bit more complicated than what your doing, but it's a nice piece of code to have in your arsenal. Basically the & operator you can think of it as "the address of"
so "the address in memory of 'str'" so you just pass the string, put the char into a string first (not hard).
istringstream is a C++ class, you can look it up. and the insertion operator '>>' is pretty self explainitry.

This will return true if the string is an integer. False if it is a standard char.... but wait.

1
2
3
4
5
6
bool isInteger(string& str)
{
   int i;
   istringstream ss(str);
   return  ( ss >> i );
}



Now what if the character is any one of these:
~ ` ! @ # $ % ^ & . ; ' " { } , [ ] ( ) * + = _- | \ / ?


----------------------------
If you need to put a string into an integer and test to see if it's valid at the same time:
1
2
3
4
5
bool isInteger(string& str, int& i)
{
   istringstream ss(str);
   return  ( ss >> i );
}
Last edited on
Topic archived. No new replies allowed.