为何tipoDeProduto[categoriaPretendida]无法正常工作?求解决方案
问题原因及解决方案
核心问题
你输入的字符'0'和整数0不是同一个值:字符'0'的ASCII码是48,直接用它作为数组索引时,会访问tipoDeProduto[48]——而你的数组只有5个元素(索引范围0-4),这属于数组越界访问,会触发未定义行为,所以程序无法正常输出。
两种修复方案
方案1:改用整数类型读取输入
将存储分类编号的变量改为int类型,直接读取整数输入,避免字符与整数的混淆:
#include <stdio.h> int main() { char tipoDeProduto[] = {'C', 'A', 'S', 'R', 'L'}; int categoriaPretendida; // 改为int类型 printf( " 0 - Cerveja\n 1 - Agua\n 2 - Sumo Natural\n 3 - Refrigerante\n 4 - Leite\n" ); printf("\n Choose the pretended category: "); scanf("%d", &categoriaPretendida); // 用%d格式符读取整数 printf(" You chose the category %c\n", tipoDeProduto[categoriaPretendida]); return 0; }
方案2:保留char类型,将字符转换为整数
如果坚持使用char类型,需要把输入的字符转换为对应的整数(减去字符'0'的ASCII值),同时跳过输入时的空白字符(比如回车):
#include <stdio.h> int main() { char tipoDeProduto[] = {'C', 'A', 'S', 'R', 'L'}; char categoriaPretendida; printf( " 0 - Cerveja\n 1 - Agua\n 2 - Sumo Natural\n 3 - Refrigerante\n 4 - Leite\n" ); printf("\n Choose the pretended category: "); scanf(" %c", &categoriaPretendida); // 前面加空格跳过空白字符 categoriaPretendida -= '0'; // 将字符'0'-'4'转为整数0-4 printf(" You chose the category %c\n", tipoDeProduto[categoriaPretendida]); return 0; }
额外优化:输入验证
为了避免用户输入无效值(比如大于4的数字或非数字字符),可以添加输入验证逻辑:
#include <stdio.h> int main() { char tipoDeProduto[] = {'C', 'A', 'S', 'R', 'L'}; int categoriaPretendida; printf( " 0 - Cerveja\n 1 - Agua\n 2 - Sumo Natural\n 3 - Refrigerante\n 4 - Leite\n" ); printf("\n Choose the pretended category: "); // 验证输入是否为0-4之间的有效整数 if (scanf("%d", &categoriaPretendida) != 1 || categoriaPretendida < 0 || categoriaPretendida > 4) { printf("Invalid input! Please enter a number between 0 and 4.\n"); return 1; } printf(" You chose the category %c\n", tipoDeProduto[categoriaPretendida]); return 0; }
内容的提问来源于stack exchange,提问作者Miguel F
相关产品推荐
相关产品推荐

