开发者

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).


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.


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


'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);


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");
}


'1' and 1 are not the same.


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


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

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


That's because:

case '1':

is not the same as:

case 1:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜