2017-08-11 7 views
0

生徒の資格情報を入力して印刷するために、次のプログラムを作成しました。しかし、2人の生徒の記録を入力すると(入力可能な最大レコード数)、それは印刷されません。 ここにプログラムがあります。誰かが間違いを指摘できますか?ありがとうございました。構造のメンバーを印刷するには?

#include<stdio.h> 
#include<string.h> 

struct student 
{ 
    char name[20]; 
    char mobile_no[10]; 
    char class[5]; 
}; 

int main() 
{ 
    static struct student s[2]; 
    int m=0,n=0,i; 
    char c; 
    printf("Enter the name , mobile_no and class of the students\n"); 
    while((scanf("%c",&s[m].name[n]))!= EOF) 
    { 
     for(n=0; n<=19; n++) 
      scanf("%c",&s[m].name[n]); 
     for(n=0; n<=9; n++) 
      scanf("%c",&s[m].mobile_no[n]); 
     for(n=0; n<=4; n++) 
      scanf("%c",&s[m].class[n]); 
     scanf("%c",&c); //scans for the newline character \n 
     n = 0; 
     m++; 
    } 

    for(i=0 ; i<m ; i++) 
    { 
     printf("%s%3s%3s\n",s[i].name,s[i].mobile_no,s[i].class); //prints the structure 
    } 
} 
+1

そして、それは何を印刷しない "それはそれらを印刷していませんか"?あなたは何を入力し、どのような出力を期待していますか?名前が19文字以下の場合はどうしますか? – Gerhardh

+1

空行と適切なインデントをコードに挿入すると、そのコードを読んでいる人の数が大幅に増える可能性があります。 – Gerhardh

+0

データを読み取るために使用されるメカニズムは奇妙です。ユーザは名前の開始前に文字を入力しなければなりません( 'while()'の中の 'scanf()'はそれを読み込みます)、名前には19文字をタイプします。スペースを取らずに、ユーザーは9文字の電話番号を入力する必要があります。スペースを使わずに、クラスの4文字とコードは、改行と見なされるもう1つの文字を読み込みます。このコードでは、文字列のいずれかがNULLで終了することは保証されません。これは多くの理由でそれを行う間違った方法ですが、それは計数だけではありません。 –

答えて

-1

私は家の仕事はしませんが、あなたは幸いです。構造体の文字列に宣言されたものより長く入力することはできないことを覚えています - 1。

struct student 
{ 
    char name[20]; 
    char mobile_no[10]; 
    char _class[5]; 
}; 

int read_students(struct student *s) 
{ 
    int m = 0; 
    printf("Enter the name , mobile_no and class of the students. Name == exit for exit\n"); 
    while (1) 
    { 
     char tmp[20]; 
     printf("Name: "); 
     scanf("%s", tmp); 
     if (!strcmp(tmp, "exit")) break; 
     if ((s = (struct student *)realloc(s, sizeof(struct student) * (m + 1))) == NULL) {m = -1; break;} 
     strcpy(s[m].name, tmp); 
     printf("Mobile: "); 
     scanf("%s", s[m].mobile_no); 
     printf("Class: "); 
     scanf("%s", s[m]._class); 

     m++; 
    } 

    if (m != -1) 
    { 
     printf("Number of students: %d\n", m); 

     for (int i = 0; i<m; i++) 
     { 
      printf("%s %3s %3s\n", s[i].name, s[i].mobile_no, s[i]._class);//prints the structure 
     } 
    } 
    return m; 
} 

main関数に:

struct student *s = NULL; 
int numberofstudentds; 

numberofstudentds = read_students(s); 
+0

whileループ全体を削除することをお勧めしますか? – Gerhardh

+0

@Gerhardh私は示唆しません - それらのループは私の人生で今まで見たことのなかで最もばかげたものです –

+0

3つの 'for'ループを含む' while'ループを 'scanf'を含む3行で置き換える答えはありません? – Gerhardh

関連する問題