我已经使用结构方法编写了简单的代码,并且在该代码中,我将字符串(名称)用作3个学生的for循环的输入。对于第一次迭代for循环中的每一行工作,因为它应该是......但问题出现在第二次迭代......在第二次迭代scanf
跳过字符串(名称)的输入...scanf函数在C编程中跳过for循环的输入
我的代码是如下:
#include<stdio.h>
struct student_data
{
char name[5];
int dsd;
int dic;
int total;
};
void main()
{
struct student_data s[3];
int i;
for(i = 0;i<3;i++)
{
printf("Enter Name of Student\n");
scanf("%[^\n]",s[i].name); // Problem occures here in
// second iteration
printf("\nEnter marks of DSD\n");
scanf("%d",&s[i].dsd);
printf("Enter marks of DIC\n");
scanf("%d",&s[i].dic);
s[i].total = s[i].dsd+s[i].dic;
}
printf("%-10s %7s %7s %7s\n ","Name","DSD","DIC","Total");
for(i=0;i<3;i++)
{
printf("%-10s %5d %6d %6d\n",s[i].name,s[i].dsd,s[i].dic,s[i].total);
}
}
无论如何,您正在使用'scanf()'错误。如果你不想读未初始化的内存,你必须检查返回值。而你不想,因为它是未定义的行为。 'scanf()'的问题在于它很难在现实生活中使用它,这就是为什么它很少被使用,但它是每个人都了解的第一件事[tag:c]。请阅读'scanf()'的文档,你可能会发现自己为什么不能正常工作,为什么它很难。 –
错误的'scanf()'。使用'scanf(“%4 [^ \ n]”,s [i] .name);'代替。 –
@AbhishekTandon如果我们使用'scanf(“%4 [^ \ n]”,s [i] .name);'。我们可以提供超过4个字符的名字吗? –