我有一个数组,它是一年中的月份:
const char *months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December" };
我想使用scanf获取用户输入,然后将相应的月份打印到用户输入的数字。
使用scanf获取用户输入,并将其保存在int变量中。然后使用方括号访问该位置并打印它。代码应该是
int a;
const char *months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December" };
scanf("%d", &a);
printf("%s",months[a]);
不要使用scanf读取数字。它的线端处理很差。注意:研究教程点- fgets sscanf指定符printf
使用fgets将stdin(用户输入)作为字符串读入。使用sscanf将其转换为整数。
char input[20];
int month_num;
printf("enter number and press ENTER: ");
fgets(input, sizeof(input), stdin);
sscanf(input,"%d",&month_num);
然后,打印出month数组的索引
printf("%s n", months[month_num]);