簡體   English   中英

scanf函數正在C編程中跳過for循環中的輸入

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

我已經使用結構方法編寫了簡單的代碼,在該代碼中,我使用3個學生的for循環將string(name)用作輸入。 對於第一次迭代,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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM