2016-07-25 4 views
0

構造メソッドを使用して簡単なコードを記述しました。そのコードでは、3人の生徒のforループを使用して文字列(名前)を入力します。 1回目の繰り返しでforループの各行が動作していますが、2回目の繰り返しで問題が発生します... scanfは文字列(名前)の入力をスキップしています...scanf関数はC言語でforループの入力をスキップしていますプログラミング

マイコードはas以下:

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

}

あなたのコードの主な問題は、あなたがサイズ2の配列である student_data s[2]を定義しますが、ループの中で、あなたがの配列のために有効である for (i=0; i<3; i++)をループしているということでした
+1

あなたは 'scanf()'を間違って使用しています。初期化されていないメモリを読み込めない場合は、戻り値をチェックする必要があります。それは未定義の動作なので、あなたはしたくないです。 'scanf()'の問題は、実用的なプログラムで有用にするのは本当に難しいことです。だからこそ使用されることはほとんどありませんが、それでもすべてが[tag:c]について学んでいます。 'scanf()'のドキュメントを読んでください。なぜそれが動作していないのか、どうしてそれがなぜ難しいのかを知ることができます。 –

+0

は 'scanf()'が間違っています。代わりに 'scanf("%4 [^ \ n] "、s [i] .name);を使用してください。私たちが 'scanf("%4 [^ \ n] "、s [i] .name);'を使用している場合、@AbhishekTandonは –

+0

です。 4文字以上の名前を付けることはできますか? –

答えて

0

この小さな変更はうまくいく:

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; 
} 
+0

thnx urの解決策は働いていましたが、%[^ \ n]がユーザーからの入力をスキップしていた理由を知りたいですか? – rushank27

+0

@ rushank27この記事を見てください:http://stackoverflow.com/questions/6083045/scanf-n-skips-the-2nd-input-but-n-does-not-why – reshad

関連する問題