写我的第一个C程序,我不能让过去这个愚蠢错误 [英] Writing my first C program and I can't get past this dumb bug
问题描述
我使用的是X code,因为我发现调试器是非常有用的。所以在调试我看,我输入后学生的名字命名[0] = \\ 0不管。但随后名称的其余部分是正确的。例如,如果我把约翰,它会回来说\\ 0,O,H,N。请帮助?
字符名称[MAX_NAME_LENGTH]
焦炭部[MAX_DEPT_LENGTH]
INT排名;
INT空= 0; 的printf(\\ n请输入学生的名字:);
scanf函数(%S,&安培;名);
的printf(\\ n请输入学生处:);
scanf函数(%S,&安培;部门);
的printf(\\ n请进入大学排名:);
scanf函数(%d个,&安培;等级);
的strcpy(studentArray [空] .name和名);
的strcpy(studentArray [空] .department,部门);
studentArray [空] .rank =排名;
做到这一点:
的printf(\\ n请输入学生的名字:);
scanf函数(%S,名);
的printf(\\ n请输入学生处:);
scanf函数(%S,部门);
的printf(\\ n请进入大学排名:);
scanf函数(%d个,&安培;等级);
请注意没有&符号的前两个调用 scanf函数
。这是因为编译器隐式转换名称
和部门
进入指针到相应的数组的第一个元素(&放大器;名称[0]
,&放大器;部门[0],当他们在一个前pression使用
)(有是expections此规则,请参见这里详情)。
这以备将来参考。
I'm using xCode because I found the debugger to be very useful. So in the debugger I see, after I enter the students name name[0] = \0 no matter what. But then the rest of the name will be correct. For example, if I put John, it will come back saying \0, o, h, n. Help please?
char name[MAX_NAME_LENGTH];
char department[MAX_DEPT_LENGTH];
int rank;
int empty = 0;
printf("\nPlease enter the students name: ");
scanf("%s", &name);
printf("\nPlease enter the students department: ");
scanf("%s", &department);
printf("\nPlease enter the students rank: ");
scanf("%d", &rank);
strcpy(studentArray[empty].name, name);
strcpy(studentArray[empty].department, department);
studentArray[empty].rank = rank;
Do this:
printf("\nPlease enter the students name: ");
scanf("%s", name);
printf("\nPlease enter the students department: ");
scanf("%s", department);
printf("\nPlease enter the students rank: ");
scanf("%d", &rank);
Note the absence of ampersands in the first two calls to scanf
. This is because the compiler implicitly converts name
and department
into pointers to the first elements of the respective arrays (&name[0]
, &department[0]
) when they are used in an expression (there are expections to this rule, see here for details).
Read this for further reference.
这篇关于写我的第一个C程序,我不能让过去这个愚蠢错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!