抱歉,如果您已经提出了这个问题,我在发布之前进行了搜索,但找不到答案。
我有以下代码:
#include<stdio.h>
#include<stdlib.h>
#define ESC 27
typedef struct{
int data[10];
int n;
} tlist;
void menu(){
printf("Options:\n");
printf("1) Show list\n");
printf("ESC) Quit\n");
}
void showList(tlist *list){
int *p;
p = &list->data[0];
if(list->n == 0){
printf("Empty list!\n\n");
}else{
for(int i=0; i<list->n; i++){
printf("%d \n", *p);
p++;
}
}
}
int main(){
char choice;
tlist list;
list.n = 10;
list.data[0] = 16;
list.data[1] = 17;
list.data[2] = 18;
list.data[3] = 19;
list.data[4] = 20;
list.data[5] = 21;
list.data[6] = 22;
list.data[7] = 23;
list.data[8] = 24;
list.data[9] = 25;
do{
menu();
scanf("%s",&choice);
switch(choice){
case '1': showList(&list);
break;
case ESC:
printf("quiting...\n");
break;
default:
printf("Invalid Choice!\n");
break;
}
}while(choice != ESC);
return 0;
}
当我运行该程序时,我将得到以下输出:
0 17 18 19 20 21 22 23 24 25
我不明白为什么第一个打印是数组中第一个元素的位置,而不是第一个元素本身。有人可以解释一下吗?
choice
是一个char
,正确的转换说明符用于scanf
isc
和not s
。
使用scanf
穿插式printf
语句打印新行(\n
)时,还必须小心。
当scanf
具有转换说明符时c
,它将把任何空格解释为一个字符,并且不等待实际的输入。因此,scanf
此处应通过包含前导空格来留出空白字符。
因此,该scanf
语句应为:
scanf(" %c", &choice);
scanf
在程序中继续进行操作之前,最好检查返回值。按照标准,scanf
返回分配的输入项目的数量,如果早期匹配失败,该数量可以少于提供的数量,甚至为零。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句