Advertisement

Switch Cases

Started by February 24, 2002 01:28 PM
6 comments, last by Magriep 22 years, 8 months ago
I have a switch case in the code, and one of the options is ''About''. After they read it, I have it say ''Press any key to go to the main menu. What command would I need to use to tell the program to go back to the switch case?
You will have to code a loop which contains the switch statement.

--

The placement of a donkey''s eyes in its head enables it to see all four feet at all times.
Advertisement
could you give me an example?
Sure. He's a trivial example...

    #include <iostream>#include <string>using namespace std;int main(){	bool loop = true;	while( loop )	{		string temp;		cout << "Please make a selection: ";		cin >> temp;		char response = temp[0];		switch( response )		{		case 'A':		case 'a':			cout << "some stuff" << "\n";			break;		case 'B':		case 'b':			cout << "some other stuff" << "\n";			break;		case 'Q':		case 'q':			cout << "exiting..." << "\n";			loop = false;			break;		}	}}    


Not that, if you do any real work within the case statements, you should do it within a function specifically for the task.

--

The placement of a donkey's eyes in its head enables it to see all four feet at all times.

Edited by - SabreMan on February 24, 2002 3:11:38 PM
...yes that would do it.
um you might want to use "toupper" or "tolower" so you dont have to check the case for both capital and non capital versions of the same character. just makes for cleaner code
C++ only allows constant switch expressions and cases; you cannot do a switch on strings or pointers.

to test various strings, you need to use if-else blocks.

OR, you could use a switch with arrays, like this:
    string* _strings;	int _stringsCount = 5;	initStrings();	string* _constStrings;	int _constStringsCount = 5;	initConstStrings();	int _case;	for(int i = 0; i < _stringsCount; i++)		if ( _strings[i].str == _constStrings[i].str ) {_case = i; break;}	switch (_case)	{	case 1:        //.....	}//eos    


Edited by - evilcrap on February 25, 2002 2:16:36 PM
Advertisement
I think that''s what he meant:

#include <iostream>
#include <string>
using namespace std;
int main(){
bool loop = true;
while( loop )
{
string temp;
cout << "Please make a selection: ";
cin >> temp;
char response = temp[0];
switch( toupper(response) )
{
case ''A'':
cout << "some stuff" << "\n";
break;
case ''B'':
cout << "some other stuff" << "\n";
break;
case ''Q'':
cout << "exiting..." << "\n";
loop = false;
break;
}
}
}


quote: Original post by EvilCrap
C++ only allows constant switch expressions and cases; you cannot do a switch on strings or pointers.


To be precise, you can only switch on expressions which evaluate to integral type, or a type which has a defined and accessible conversion to integral type. I wasn''t aware that anyone had suggested otherwise.

--

It is against the law to stare at the mayor of Paris.

This topic is closed to new replies.

Advertisement