Switch and char problems

Jul 19, 2016 at 8:27pm
Hello guys, how are you doing? Ok, so I have a problem with this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
	char a;
	cin >> a;
	switch (a)
	{
	case 'qwert':
		cout << "lala";
		break;
	}
    return 0;
}

The error says that it has too many characters in the constant. If I delete the "t" letter, it works. So it is working only with 4 characters but not 5 or above. I need it to work for long WORDS too, not only short ones.
Jul 19, 2016 at 9:35pm
'char' is short for character i.e. a SINGLE character.

So when you cin >> a, you should only be inputting 1 character. The switch and case should also then be checking for a single character.

So take a look at this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
	char a;
	cin >> a;
	switch (a)
	{
	case 'a':
		// do something
		break;
        case 'b': 
                // do something
                break;     
	}
    return 0;
}

Last edited on Jul 19, 2016 at 9:36pm
Jul 20, 2016 at 7:39am
dude i know that it works how you replied, but I want for it to work for long words too, not just a single character, is there another type that I should use instead of char or what?
Jul 20, 2016 at 7:42am
> I want for it to work for long words too
Have you learned std::string

You would need something good like a for loop to do that.
Jul 20, 2016 at 7:44am
Hint : tolower(), strcmp(), stricmp()
Jul 20, 2016 at 8:11am
i don't understand it completely
or maybe you misunderstood it, I need to input the char
Last edited on Jul 20, 2016 at 8:11am
Jul 20, 2016 at 8:20am
So you need to use char data type while simultaneously being able to work with multi-character strings? Sorry, you can't have both. Either stick with single character (i.e. char data type), or simply switch to string.

Note that switch statements don't work on std::string. So if you do decide to go with strings, you'll have to change switch-case to if's and else-if's
Jul 20, 2016 at 8:24am
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{
	char a;
	cin >> a;
	switch (a)
	{
	case 'q' : case 'w' : case 'e' : case 'r' : case 't' :
		cout << "lala";
		break;
	}
    return 0;
Jul 20, 2016 at 8:27am
a simple example would be life-changing :p
because I am trying to use if and else for string type but it says expression must have bool type (or to be convertible to bool)
Jul 20, 2016 at 8:30am
no, it worked, sorry, so dump of me using = instead of == :p
thanks for the help arslan, it worked
Jul 20, 2016 at 8:34am
Good to hear :)
Jul 20, 2016 at 9:07am
Good to hear :)


Well in terms of the OP arriving at a solution - but your answers were terrible.
Topic archived. No new replies allowed.