我使用结构方法编写了简单的代码,在该代码中,我使用字符串(名称)作为输入,使用3个学生的for循环。对于第一次迭代,for循环中的每一行都应该正常工作....但问题出现在第二次迭代中...在第二次迭代中scanf
正在跳过字符串(名称)的输入......
我的代码如下:
#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);
}
}
答案 0 :(得分:0)
您的代码的主要问题是您定义了student_data s[2]
这是一个大小为2的数组,但是在循环中,您循环for (i=0; i<3; i++)
,它对大小为3的数组有效。这个小修改可以正常工作:
int main()
{
struct student_data s[2]; // array of size 2
int i;
for(i=0; i<2; i++) // i will have values 0 and 1 which is 2 (same as size of your array)
{
printf("Enter Name of Student\n");
scanf("%s", s[i].name);
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<2; i++) // same mistake was repeated here
{
printf("%-10s %5d %6d %6d\n",s[i].name,s[i].dsd,s[i].dic,s[i].total);
}
return 0;
}