Switch and char problems

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.
'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
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?
> 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.
Hint : tolower(), strcmp(), stricmp()
i don't understand it completely
or maybe you misunderstood it, I need to input the char
Last edited on
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
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;
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)
no, it worked, sorry, so dump of me using = instead of == :p
thanks for the help arslan, it worked
Good to hear :)
Good to hear :)


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