gpt4 book ai didi

c - scanf函数在C编程中跳过for循环中的输入

转载 作者:行者123 更新时间:2023-11-30 16:58:47 27 4
gpt4 key购买 nike

我使用结构方法编写了简单的代码,在该代码中,我使用 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);
}

}

最佳答案

您的代码的主要问题是您定义了 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;
}

关于c - scanf函数在C编程中跳过for循环中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38566473/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com