yusr.
yusr.

Reputation: 13

A problem with (switch) in C

scanf("%ld",&l);
printf ("l=%ld",l);
switch (l)
{
case'1':
XOR(&matrix1[10],&matrix2[10],m);
break;
case'2':
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}

When the program reaches switch, no matter what I enter (whether it's wrong or right), the program keeps showing the massage (Wrong input), though I've entered a right number (1 or 2).

Upvotes: 1

Views: 315

Answers (8)

ldav1s
ldav1s

Reputation: 16315

That's because:

case '1':

is not the same as:

case 1:

The second one is the one you seem to be expecting.

Upvotes: 0

erenon
erenon

Reputation: 19148

'1' is a char, the ASCII representation of the digit 1. Use plain 1 instead.

case 1:
    /*...*/
    break;

Upvotes: 0

Goz
Goz

Reputation: 62333

But you aren't reading a character but your cases are characters. Re-write as follows:

switch (l)
{
case 1:
XOR(&matrix1[10],&matrix2[10],m);
break;
case 2:
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}

Upvotes: 1

OmnipotentEntity
OmnipotentEntity

Reputation: 17131

Because your switch is relying on an integer. Whereas you're taking in a string. You'll need to run l through atoi first.

Upvotes: 0

shybovycha
shybovycha

Reputation: 12275

'1' != 1

Note: '1' is nearly 60 or something like that, 'cause single quotes mean "using char" (or it's ASCII code). Try removing 'em from your switch cases:

scanf("%ld",&l); printf ("l=%ld",l); switch (l) { case 1: XOR(&matrix1[10],&matrix2[10],m); break; case 2: AND(&matrix1[10],&matrix2[10],m); break; default: printf("\n\t\tWrong input"); }

Or you can change your input from numeric to char:

scanf("%c", &l);

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215607

'1' and 1 are not the same.

Upvotes: 0

Paul R
Paul R

Reputation: 213200

Change your case labels from

case'1':
  ...
case'2':
  ...

to

case 1:
  ...
case 2:
  ...

Explanation: your switch value is an integer, not a character, hence you need integer constants for your case labels, not character constants.

Upvotes: 5

icanhasserver
icanhasserver

Reputation: 1064

Your case should be case 1 and not case '1'.

Upvotes: 1

Related Questions