Text cases

How do you use text in cases? Observe the following code snippet.

cin >> spam;
switch (spam) {
case nothing:
cout << "Screw you";
break;
}

Any idea? The purpose of that code snippet is to see if the spam variable concludes of NOTHING, and if so, says Screw you. I don't use if statements as switch statements are better.
If you don't get what my question is: Please ask. Thank you for your time and patience
> How do you use text in cases

You don't. Not directly.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const char* const text[] = { "abc", "def", "ijkl" } ;
enum { N = sizeof(text) / sizeof(text[0]) } ;

std::string str ;
std::cin >> str ;

int pos = 0 ;
for( ; pos < N ; ++pos ) if( str == text[pos] ) break ;

switch(pos)
{
    case 0 : // "abc"
        // ...
        break ;
    case 1 : // "def"
        // ...
        break ;
    case 2 : // "ijkl"
        // ...
        break ;
    default : // something else
        // ...
        ;
    }
This may not be too helpful, but you can do this in other languages, such as D.
http://dlang.org/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import std.stdio;

void main()
{
	write("Input some text: ");

	string text = readln();

	switch (text)
	{
		case "screw you\n": writeln("Well screw you too!"); break;
		case "hello\n": writeln("Hello!"); break;
		default: writeln("Blah blah."); break;
	}
}


The reason why you can't do it in C and C++ is that they "see" arrays as pointers, so when you compare them, you actually compare two numbers representing the arrays' addresses and not their contents.

And if you use std::string, it simply doesn't work with switch(), although it should. I guess this is because it's not a built-in type.
> I guess this is because it's not a built-in type.

No. It is because the expression in the case label must be a constexpr which can be implicitly converted to an integral type.

This is fine:
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
struct A
{
    constexpr A( int i ) : a(i), b(i*2) {}

    constexpr operator int () const { return a + b ; }

    private:
        int a ;
        int b ;
};

int main()
{
    constexpr A a[] = { {2}, {5}, {12} } ;

    int i ;
    std::cin >> i ;

    switch(i)
    {
        case a[0] :
            // ...
            break ;

        case a[1] :
            // ...
            break ;

        case a[2] :
            // ...
            break ;

        default :
            // ...
            ;
    }
}
Last edited on
@ JLBorges: my mistake, thanks.
http://ideone.com/qbrxI
john924xps wrote:
I don't use if statements as switch statements are better.
Not always. In this situation I think if statements are better.
Thanks for the help, all of you! Appreciate it!
Here: Have a cookie.
Topic archived. No new replies allowed.