简体   繁体   English

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

[英]scanf function is skipping input in for loop in C Programming

I have write simple code using structure method and in that code I am taking string(name) as input using for loop for 3 students. 我已经使用结构方法编写了简单的代码,在该代码中,我使用3个学生的for循环将string(name)用作输入。 For 1st iteration each line in for loop is working as it should be.... but problem comes on second iteration... in second iteration scanf is skipping input for string (name)... 对于第一次迭代,for循环中的每一行都应按预期方式工作。...但是问题出在第二次迭代中……在第二次迭代中scanf跳过了字符串(名称)的输入...

My code is as below : 我的代码如下:

#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);
}  

} }

The main problem with your code was that you defined the student_data s[2] which is a array of size two, but in the loop, you are looping for (i=0; i<3; i++) which is valid for an array of size 3. This small modifications will work fine: 代码的主要问题是,您定义了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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM