Problem with Switch,do-while

Hello all. I'm currently tinkering with C++ and have been playing with a text adventure. My problem is that I'm trying to make a switch statement that if the switch defaults it will just repeat the switch and ask the question until an adequate answer is provided. I've got it working with only numbers but say somebody is being crazy and doesn't type the number options and instead just types any random text and hits enter it just starts spamming the console with the do while loop. The code looks like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  do {
		printf("\n\n1.\"STUPID SUN!\"\n");
		printf("2.\"Time to get up.\"\n");
		printf("3.\"Whats the point of waking up?\"\n");
		printf("4.Throw your alarm across the room\n");
		scanf("%d",&Choice);
	
		switch(Choice){
			case 1: printf("Man you're angry\n"); done = true; break;
			case 2: printf("Sure is\n"); done = true; break;
			case 3: printf("Sad much?\n"); done = true; break;
			case 4: printf("...really?\n"); done = true; break;
			default: printf("I'm sorry can you repeat that?\n\n\n");done = false; break;
		}
	}while (!done);

the done boolean is declared at the top of main because I plan on using this for all the questions.
is it possible to make a case string? or something of that nature? Any ideas and help would be greatly appreciated. I'm sure this is really simple but there's a reason I'm in the beginners section :P
Hi,
switch can't work with strings. Hovewer, you can use if/else to do it.
(Because I see You use cstdio instead of iostream, I used cstring in example - you can replace it by c++ string if you want).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  char choice[64] = {0};

  fgets(choice, sizeof(choice), stdin);

  if (strcmp(choice, "rvalue1\n") == 0)
  {
     // do something
  }
  else if (strcmp(choice, "rvalue2\n") == 0)
  {
     // do something other
  }
  else if (strcmp(choice, "rvalue3\n") == 0)
  {
     // do something other
  }
  else
  {
    // This is analogous of 'default' brench. 
  }
Last edited on
Is there any way to not accept a string within the switch so I can still use it? The switch statement is a lot cleaner since I'm making a text adventure and the person playing is expected to put in a number but if they decide to try a string I don't want the game to completely wig out. If the if/else statements are my only option then its my only option but I'd really like to believe there's got to be some way to do this
You can use strcmp and getline to get data.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>// std namespace
#include <string.h>// strcmp

int main(void) {// main
	std::string name;// this is raw data for the name
  
	std::cout << "I will check your name: ";// ask user for name
	std::getline (std::cin,name);// gets the raw data and puts it in name
	
	if(!strcmp(name.c_str(),"MyName")) {// strcmp compares name with master's name
		std::cout << "Hi master.";// if we find match, tell master we recognize
	} else {// otherwise,
		std::cout << "You are not my master.";// tell the user they are a imposter
	}
	
	std::cin.ignore();// keep program up
  	return 0;// end program with success (0)
}// main end 



Oh woops, looks like I took too long to respond. Well, you can still use this code as an example. Good luck!


//////////////////////
No, you cannot use switch with anything other than char or int.
Last edited on

Is there any way to not accept a string within the switch so I can still use it?
The switch statement is a lot cleaner since I'm making a text adventure and the person playing is expected to put in a number but if they decide to try a string I don't want the game to completely wig out.


I don't sure did I understand you well. Would you like to do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  ask user for input
  
  if (input is string)
  {
    ignore it and go on
  }
  else
  {
     switch(input)
     {
        case 1:...
        ...
        case 2:...
        ...
     }
  }


?
Last edited on
Oh wow I can't believe I didn't think of doing that! Thank you usandfriends but I think sw143 is on the right track. Yes that is the exact order of operations I'm trying to complete. I just didn't even think of doing an if/else
so what I think I need to do is make a function for the user input then use your if/else example with the switch statement inside the else brackets and the user input function in the if brackets?
like so..
1
2
3
4
5
6
7
8
9
10
11
12
if (input is string)
{
    repeat question
} 
else 
   {
      switch(input){
             case 1:....
             case 2:....
             etc.
       }
    }


and is checking if a value is a string as easy as

 
if (value === string)
??
You can write own function to check does given string is a correct number by
scanning characters in string.
Correct decimal number should NOT contains any non-decimal characters and contains at least one decimal.
Please look at ASCII table before look at example.

Here is example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//
// Check does given buffer is a correct number.
//
// buf[] - pointer to zero terminated ascii string (IN).
//
// RETURNS: 1 if buffer contains correct decimal number,
//          0 otherwise.
//

int IsNumber(const char *buf)
{
  int containsDecimal = 0;
  int canBeANumber    = 1;
  int goOn            = 1;
  
  //
  // Skip white characters on left side.
  //
  
  while(*buf && isspace(*buf))
  {
    buf++;
  }
  
  //
  // Scan whole buffer for non-decimal chars,
  // until string's end reached and we still have
  // expectancy, that buffer can be a correct number.
  //
  
  for (int i = 0; goOn; i++)
  {
    switch (buf[i])
    {
      //
      // Decimal character. Go on,
      // string can be stiil a number.
      // Save, that string contains at least one decimal.
      //

      case '0'...'9':
      {        
        containsDecimal = 1;
        
        break;
      }

      //
      // Stop on first white character or when string ends. 
      // Don't go on longer.
      //
      // NOTE: You may want to treat white characters in the other way.
      //       It depends on what You need.
      //
      
      case 0:
      case 13:
      case 10:
      case ' ':
      case '\t':
      {
        goOn = 0;
        
        break;
      }
      
      //
      // Something other. We know it can't be a correct number longer.
      //
      
      default:
      {
        canBeANumber = 0;
      }
    }
  }
  
  //
  // If we passed all test, we adjust it's a correct number.
  //
  
  return canBeANumber;
}    

Last edited on
Topic archived. No new replies allowed.