如何在 switch 语句中使用字符串?现在我在 switch 语句中使用了字符串的第一个字母。这是我的代码。我想使用 char a、b、c 中的整个字符串作为 switch 中的输入。怎么做?
int main()
{
char input[10];
int x, y, i;
int AX;
char a[] = "ADD";
char b[] = "PRT AX";
char c[] = "EXIT";
for (i = 0; i < 100; i++)
{
printf("\nType ADD following the two numbers to be added\n");
printf(" PRT AX to display the sum\n");
printf(" EXIT to exit program\n");
printf("---->");
scanf("%s", &input);
switch (input[0])
{
case 'A':
printf("\nEnter two numbers you want to add:\n");
scanf("%d %d", &x, &y);
break;
case 'P':
printf("Sum: %d\n\n", x + y );
break;
case 'E':
exit(0);
default:
i++;
}
}
return 0;
}
最佳答案
尝试类似的事情
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char input[10];
int x, y, i;
const char * a[3] =
{
"ADD",
"PRT AX",
"EXIT",
};
enum CHOICE { ADD, PRT_AX, EXIT, WRONG } choice;
for ( i = 0; i < 100; i++ )
{
size_t n;
printf( "\nType ADD following the two numbers to be added\n" );
printf( " PRT AX to display the sum\n" );
printf( " EXIT to exit program\n" );
printf( "---->" );
fgets( input, sizeof( input ), stdin );
n = strlen( input );
if ( n && input[n-1] == '\n' ) input[n-1] = '\0';
choice = ADD;
while ( choice != WRONG && strcmp( a[choice], input ) != 0 )
{
choice = ( enum CHOICE )( choice + 1 );
}
switch ( choice )
{
case ADD:
printf( "\nEnter two numbers you want to add:\n" );
scanf( "%d %d", &x, &y );
fgets( input, sizeof( input ), stdin );
break;
case PRT_AX:
printf( "Sum: %d\n\n", x + y );
break;
case EXIT:
puts( "Exiting..." );
exit(0);
default:
i++;
}
}
return 0;
}
还要考虑到您应该使用 fgets
读取整行,然后应用 sscanf
。
关于c - C语言中如何切换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27202510/