I'm writing a game and I'm wound up in needing a console for simple text input; filenames and simple values.
Using SDL, my console looks the following at it's simplest:
class Console
{
public:
typedef std::list<String> InputList;
enum Result
{
NOTHING = 0,
ENTERED,
ESCAPED
};
static const String& GetInput() { return input; }
static Result Query(SDLKey lastKey)
{
if(lastResult == ENTERED || lastResult == ESCAPED)
{
input.clear();
}
switch (lastKey)
{
case SDLK_a:
case SDLK_b:
case SDLK_c:
case SDLK_d:
case SDLK_e:
case SDLK_f:
case SDLK_g:
case SDLK_h:
case SDLK_i:
case SDLK_j:
case SDLK_k:
case SDLK_l:
case SDLK_m:
case SDLK_n:
case SDLK_o:
case SDLK_p:
case SDLK_q:
case SDLK_r:
case SDLK_s:
case SDLK_t:
case SDLK_u:
case SDLK_v:
case SDLK_w:
case SDLK_x:
case SDLK_y:
case SDLK_z:
case SDLK_0:
case SDLK_1:
case SDLK_2:
case SDLK_3:
case SDLK_4:
case SDLK_5:
case SDLK_6:
case SDLK_7:
case SDLK_8:
case SDLK_9:
case SDLK_SLASH:
case SDLK_BACKSLASH:
case SDLK_PERIOD:
case SDLK_COMMA:
case SDLK_SPACE:
case SDLK_UNDERSCORE:
case SDLK_MINUS:
input += static_cast<char> (lastKey);
lastResult = NOTHING;
break;
case SDLK_RETURN:
lastResult = ENTERED;
break;
case SDLK_ESCAPE:
lastResult = ESCAPED;
break;
}
return lastResult;
}
protected:
static Result lastResult;
static String input;
};
This would be called from the application's main event loop, if the console is active and the last event was a keypress, then the result of the input is processed at a state where it's necessary.
Of course, it looks incredibly awkward... What's a better way to implement a simple console that can be easily rendered in my game's window? (Not going anywhere near to highly unportable solutions like having to reroute std::cout or writing code to bring up a UNIX console etc.)
One suggestion I would offer is to use if statements instead of a switch in this case:
if(lastKey == SDLK_RETURN)
lastResult = ENTERED;
else if(lastKey == SDLK_ESCAPE)
lastResult = ESCAPED;
else if(lastKey >= SDLK_SPACE && lastKey <= SDLK_z)
{
input += static_cast<char> (lastKey);
lastResult = NOTHING;
}
I took some liberties and included some characters that you didn't have in your code above, such as the ampersand, quotes, parentheses, brackets, etc. If you don't want those keys, you can add a few more if statements to break it down a bit more.
This assumes that the enum for the keys doesn't change a lot. If it does change a lot you may be better off with what you had.
Related
I wrote this part of code and a series of error are being shown. The above mentioned error being the first. What is wrong in the code?
void direction(char ch)
{
switch(ch)
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
You can choose to omit the opening and closing braces for a switch statement only when you have only one case in your switch block as shown below:
void direction(char ch)
{
switch(ch)
case 'w': if(dirn!=3){dirn=1;}
}
But, if you have got multiple cases to deal with like in your case then you must enclose them inside a pair of opening and closing braces to create a code block for the switch statement as shown below:
void direction(char ch)
{
switch(ch)
{//opening brace for starting of statement block
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
}//closing brace for closing of statement block
So you will have to either remove all the cases but one OR add the pair of braces to create statement block. In all other cases your code won't compile successfully.
You have forgotten the switch braces :
void direction(char ch)
{
switch(ch)
{
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
}
}
switch statement requires braces block, where all labels including default one should be:
switch(ch)
{
case 'w': if(dirn!=3) dirn=1;
break;
case 'a': if(dirn!=2) dirn=4;
break;
case 's': if(dirn!=1) dirn=3;
break;
case 'd': if(dirn!=4) dirn=2;
break;
default:
break;
}
The statement after switch must be a compound statement to contain case, default and break. Break got a special meaning here, different from loops. If brace was omitted only next line after switch is part of its statement.
I'm not understanding why my switch statement is not working.
I've chopped it up since it was rather long, but the user is supposed to input a character to "selection1' & "selection2" and then I pass those as a parameter to my validSelection() function. The validSelection function is supposed to test the characters for the valid entries and deny all others by returning a boolean.
bool validSelection(char selection)
{
switch (selection)
{
case "R":
case "r":
case "P":
case "p":
case "S":
case "s":
return true;
default:
return false;
}
}
cin >> selection1;
cin >> selection2;
if (validSelection(selection1) && validSelection(selection2))
selection1 and selection2 both are char data types.
As #CaptainObvlious has already pointed out, anything between double-quotes "" is considered as string. However, you ant to pass the integer value to the switch. For the same, you have to put the characters inside single-quotes ''.
You may need to change our code as below.
bool validSelection(char selection)
{
switch (selection)
{
case 'R':
case 'r':
case 'P':
case 'p':
case 'S':
case 's':
return true;
default:
return false;
}
}
I used getchar() to stop the while string. My problem is that it does stop the while string if I type one or two characters, if the user input is more the two characters nothing happens.
here is the code:
printf("enter srting\n");
while ((tmp=getchar()) !='\n') { \\here is my problem
count_letters++;
/* COUNTING WORD THAT START WITH LETTES L,A,C,H */
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
} /* end of count letters while */
n1=n2;
n2=n3;
n3=tmp;
if (n1=='H' && n2=='Y' && n3=='A') {
count_hya++;
}
} /* end of getchar while */
printf("\n");
printf("%d", count_letters);
I believe it's your code :
"while (count_letters%3==0))"
is something wrong!
because when you type more than three letters,your variable "count_letters" will add to 3 due to the code:"count_letters++;".
May be you could change the "while" to "if" and see if it's working correctly~
Here's the problem:
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
}
when your the third character is read, your program enters a infinite loop because of (count_letters%3==0)
I can't understand the purpose of your code.
I suggest using gets() and string manipulation functions because you are processing an entire line. (see string.h)
getchar() is also less efficient compared with gets() + for-loop
I'm having difficulties seeing why one way works and way doesn't.
I have;
switch (key)
{
//If Game over Label is visible, enable the m and e buttons
if(mGameOverLabel->GetVisible())
{
case 'm': case 'M':
ResetScreen();
break;
case 'e': case 'E':
// //Exit the game
Stop();
break;
} else {
case ' ':
mSpaceship->Shoot();
break;
default:
break;
}
For the case of the m and e, even though mGameOverLabel is set to false at this current time, I can still press M and E and these will react according to the methods, but If I change it to this for M it will then only work when I need it too. Am I missing something here?!
switch (key)
{
//If Game over Label is visible, enable the m and e buttons
case 'm': case 'M':
if(mGameOverLabel->GetVisible()) ResetScreen();
break;
}
The switch basically does a goto to the appropriate case label. Any logic above the case will not be executed.
I'm creating a console app and using a switch statement to create a simple menu system. User input is in the form of a single character that displays on-screen as a capital letter. However, I do want the program to accept both lower- and upper-case characters.
I understand that switch statements are used to compare against constants, but is it possible to do something like the following?
switch(menuChoice) {
case ('q' || 'Q'):
//Some code
break;
case ('s' || 'S'):
//More code
break;
default:
break;
}
If this isn't possible, is there a workaround? I really don't want to repeat code.
This way:
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 's':
case 'S':
//More code
break;
default:
}
More on that topic:
http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript
The generally accepted syntax for this is:
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 's':
case 'S':
//More code
break;
default:
break;
}
i.e.: Due the lack of a break, program execution cascades into the next block. This is often referred to as "fall through".
That said, you could of course simply normalise the case of the 'menuChoice' variable in this instance via toupper/tolower.
'q' || 'Q' results in bool type result (true) which is promoted to integral type used in switch condition (char) - giving the value 1. If compiler allowed same value (1) to be used in multiple labels, during execution of switch statement menuChoice would be compared to value of 1 in each case. If menuChoice had value 1 then code under the first case label would have been executed.
Therefore suggested answers here use character constant (which is of type char) as integral value in each case label.
Just use tolower(), here's my man:
SYNOPSIS
#include ctype.h
int toupper(int c);
int tolower(int c);
DESCRIPTION
toupper() converts the letter c to upper case, if possible.
tolower() converts the letter c to lower case, if possible.
If c is not an unsigned char value, or EOF, the behavior of these
functions is undefined.
RETURN VALUE
The value returned is that of the converted letter, or c if the
conversion was not possible.
So in your example you can switch() with:
switch(tolower(menuChoice)) {
case('q'):
// ...
break;
case('s'):
// ...
break;
}
Of course you can use both toupper() and tolower(), with capital and non-capital letters.
You could (and for reasons of redability, should) before entering switch statement use tolower fnc on your var.
switch (toupper(choice))
{
case 'Q':...
}
...or tolower.
if you do
case('s' || 'S'):
// some code
default:
// some code
both s and S will be ignored and the default code will run whenever you input these characters. So you could decide to use
case 's':
case 'S':
// some code
or
switch(toupper(choice){
case 'S':
// some code.
toupper will need you to include ctype.h.