How to make prog read 2 digit char inputs ?

Hello :)

Having a little problem with input 2 digit numbers with a char data type.

Assume this simplified program :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main()
{
start:	
	char x;
	cout<< "type a number\n";
	cin>>x;
	switch (x){
		case '1':
			cout << "1\n";
		break;
		case '10':
			cout << "10\n";
		break;
		case 'r':
			cout << "restart\n";
			goto start;
		break;
			}
goto start;
return 0;
}


My question/problem would be in this code, how to execute Case '10'

Please help me on this.

Thanks on advance :)
10 can never be a char. Use an std::string instead of a char, and then in the case statements you'll need to use quote marks like

case "1": instead of case '1':
Hi,

the problem with this code is that you only input a single digit and then
in your switch statement you are trying to compare it with a two digit number case '10':

You will either need to input as a string or as an integer

if as a string you would need to use the strcmp function.

if as an integer you would just use case 1: case 10: etc

Sorry I havent been much help,
Shredded
Thanks for the replies :)

let's say I'll use Int , how can I make it so that prog won't go haywire when the input is not a number?
Hi again,

Have altered your code to test for values other than int.
You should be able to follow what i have done.

note I put your function in a while loop to get rid of the goto (which is disliked in c++)

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
#include <iostream>
using namespace std;

int main()
{
	
	int		x;
	char	tempChar;
	bool	done = false;

	while (!done)
	{
		cout<< "type a number\n";
		
		cin>>x;

		if (cin.fail())		//something other than an int 
		{
			cin.clear();
			tempChar = cin.peek();
						
			cin.ignore(1);
			
			if (tempChar == 'r')
			{
				continue;	
			}
			else if (tempChar == 'x')	//added Exit
			{
				done = true;
				x = -1;			//to bypass switch
			}	
		}	

		switch (x)
		{
			case 1:
				cout << "1\n";
				break;

			case 10:
				cout <<"10\n";
				break;
		}
	}

	return 0;
}
Select on a string. (See the last code snippit in the last post. The whole thread is instructive, though.)
http://www.cplusplus.com/forum/general/11460/
@Shredded: Thanks for the introduction to cin.break/clear/peek and ignore
It's really helping me out here and also will in the future ^^


@Duoas: There were indeed some interesting thought paterns in that thread, no doubt I'll use some of them aswell in the future :)
Thanks for linking me there.

Last edited on
Topic archived. No new replies allowed.