Char and Int within switch

How do I use both char and int within a switch?

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
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
     int shop_pick, amount;
     int item_type;
     int inventory[11]={0};   // Non initialized arrays contain trash

     //for loops that will be used instead goto
     bool shop_loop = true;
     bool item_type_loop;
    
     while(shop_loop) {
          cout << "\n\n1)General Store          5)Bar";
          cout << "\n2)Blacksmith               6)Joe's House";
          cout << "\n3)Potions/Magic Shop";
          cout << "\n4)Weapons";
    
          cin >> shop_pick;
          switch(shop_pick) {
               case 1: 
                    cout << "\n\nWelcome To The General store!" << endl;
                    cout << "1) 1 Gallon Water:"                << endl;
                    cout << "2) 1 lb Meat:"                     << endl;
                    cout << "3) 5 lbs Meat:"                    << endl;
                    cout << "4) Assortment of Spices/Herbs:"    << endl;
                    cout << "5) Wool Gloves:"                   << endl;
                    cout << "6) Wool Coat:"                     << endl;
                    cout << "7) Light Leather Boots:"           << endl;
                    cout << "8) Pack of 5 Torches:"             << endl;
                    cout << "9) Pack of 5 Lanterns:"            << endl;
                    cout << "10) 1 Quart of Oil:"       << endl << endl;    
               
                    item_type_loop = true;
                    while(item_type_loop) {  
                         cout << "Press 1 - 10 and Then Enter To Purachase An Item. Press 'b' To Go Back To The \nShop List. When done, press 'd'";
                         cin  >> item_type;
                         switch(item_type) {
                              case 1: 
                              case 2:
                              case 3:
                              case 4:
                              case 5:
                              case 6:
                              case 7:
                              case 8:
                              case 9:
                              case 10:
                                   cout << "Enter amount: ";
                                   cin  >> amount;
                                   inventory[item_type]+=amount;
                                   cout << "Type " << item_type << " has " << inventory[item_type] << " items in it" << endl;
                                   break;
                              
                              case 'b':
                                   item_type_loop = false;
                                   break; 
                              
                              case 'd':
                                   item_type_loop = false;
                                   shop_loop = false;
                                   break; 
                              default:
                                   cout << "Incorrect Command!";     
                                   item_type_loop = false;
                                   break;
                         }           
                      
                    }
          break;
          }
     }
    system("PAUSE");
    return EXIT_SUCCESS;
}
It might be an idea to take a char variable from the user rather than an int, as this way you can read in both numbers and characters from the user. Then perform ( char == char ) comparison.

So you would do your switch comparisons like this:

1
2
3
4
5
6
7
8
9
10
case '1':
case '2':
//and so on

case 'b':
    //your code
    break;
case 'd':
    //you code
    break;


Hope this helps!
It's hard to do that because of my code under case 1 - 10.

The arrays get screwed up
You could input the item type as a string and then convert it to an integer, depending on if it was a number or a letter:
1
2
3
4
5
6
7
8
9
10
11
12
13
std::string item_type_str;

std::cin >> item_type_str;

// Did the user enter a single letter?
if(item_type_str.size() == 1 && isalpha(item_type_str[0]))
{
    item_type = item_type_str[0]; // use char code
}
else // Assume user entered a number
{
    std::istringstream(item_type_str) >> item_type; // convert from decimal string
}

You may also want to check for errors at every step of the way...
Last edited on
I'm new to C++ and can't say I fully understand your code Galik
Your variable item_type is an integer. So when the user types in a value for it the compiler converts whatever the user types directly into a binary number. Doing it that way means that you loose the original characters that the user typed in.

If you make item_type a char, then you retain the character that is typed in but you have limited your numerical range to between 0 and 9.

So my option is to read in a std::string, which captures what the user inputs without modifying it so that we can test what the user entered before deciding how to convert it to our integer item_type.

With a std::string like item_type_str you can find out how many letters it contains with the size() function:

if(item_type_str.size() == 1) // test if only a single character was entered.

You can access each individual character of the std::string using [] with [0] being the first character.

So item_type_str[0] is the first character that the user typed.

There is a standard library function isalpha() to test if a character is a letter, rather than a number or a space or a symbol:

So isalpha(item_type_str[0]) tests the first character the user entered to see if it is a letter "a-z, A-Z" rather than anything else (a digit for example).

If it was a letter then we can simply use it as-is and compare it with known letters 'b', 'd', etc...

Otherwise, if it was a number, it could be several characters long and needs converting into an integer. To do this conversion I used a std::istringstream. By putting what the user entered into a std::istringstream I am giving myself another opportunity to read the user input again but this time into an integer, rather than a std::string.

std::istringstream(item_type_str) creates an input stream out of the input a bit like cin. We can thus read our integer directly from it like this:

std::istringstream(item_type_str) >> item_type.

That is a short way to do this:
1
2
std::istringstream iss(item_type_str); // create an input stream from our string
iss >> item_type; // read our integer from our new input stream. 


I hope that makes things a little clearer... ;o)
Last edited on
That really helped, but I am still a little confused on the last part:

Otherwise, if it was a number, it could be several characters long and needs converting into an integer. To do this conversion I used a std::istringstream. By putting what the user entered into a std::istringstream I am giving myself another opportunity to read the user input again but this time into an integer, rather than a std::string.

std::istringstream(item_type_str) creates an input stream out of the input a bit like cin. We can thus read our integer directly from it like this:

std::istringstream(item_type_str) >> item_type.

That is a short way to do this:

std::istringstream iss(item_type_str); // create an input stream from our string
iss >> item_type; // read our integer from our new input stream.


What exactly is istringstream iss doing? Are you inputing for item_type and then converting it from a string to an int?
This might not be 100% correct as I've never really used the #include <sstream> class before but here goes!

The "istream::operator>>" operator has multiple overloads to handle a wide variety of destination types (see here: http://cplusplus.com/reference/iostream/istream/operator>>/ you might need to cut and paste this link).

std::istringstream iss(item_type_str); // create an input stream from our string
iss >> item_type; // read our integer from our new input stream.


From what I understand after having read the documentation, is that the ">>" operator understands that the destination variable is of type int and uses the overload for integers: istream& operator>> (int& val );.

This then reads out the contents of what is held in the string item_type_str, converts it's contents to type int then assigns it to the int item_type.

The added bonus of using the <sstream> class is that it has built in error detection and handling in the form of stringstream::fail() among others (see documentation). So if you try to read a character into an integer variable, the assignment will fail and you can test for this by using the aforementioned method.

This is the beauty of using the <sstream> class.

Like I said, I'm not a pro this is my interpretation. If anyone finds any errors in my explanation please feel free to correct me! :D

Try the code and I'm sure you'll get it!

Hope this helps!
@lnk2019

That about covers it.

When you type something in at the keyboard is it in the form of a string. But if you ask the computer for an int like this:
1
2
3
int i;

cin >> i;

What the computer does is convert what you type into an integer.

So if you type three characters '1' then '4' then '7' - those three characters will be converted into a single integer binary number with the value 147.

If, on the other hand, you ask the computer for a string, then you get the three characters that the user typed in unchanged. They are not in number form (binary integer) and so the computer can not use them to do arithmetic, like addition or multiplication. They are just plain text.

The std::istringstream() class lets us create our own input just like the input we get from the keyboard that is called cin. Instead of waiting for the user to type something like we do with cin, we mut tell our std::istringstream what it must contain before we use it.



Last edited on
closed account (zwA4jE8b)
you can still do your switch case with just a char. 1-10 can be chars.

so if you make
char item_type
and
inventory[item_type - 48]+=amount;

if you familiarize yourself with ascii you will see that '0' char code in ascii is 48. so '1' is 49

so therefore 49 - 48 = 1 - this converts the char 1 to integer 1 .... and so on
this works for 0 - 9. which is 10 options!!!

I know 0 - 9 looks a little silly though. you could come up with a way to handle 1 - 10.
Last edited on
closed account (zwA4jE8b)
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
char *item_type = new char[2];
int itemtypeint;
cin >> item_type;

switch(item_type) {
case 1: 
    if (item[0] == '1') // tests for 1
	itemtypeint = 0;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
    if (item_type[0] == '1' && item_type[1] == '0') // tests for 10
	 itemtypeint = 9;
    cout << "Enter amount: ";
    cin  >> amount;
    inventory[itemtype]+=amount;
    cout << "Type " << item_type << " has " << inventory[item_type] << " items in it" << endl;
    break;


or something like that....
thanks everyone! Making more sense now :D
Topic archived. No new replies allowed.