2017-08-11 119 views
0

我做了以下程序输入学生的凭证,然后打印出来。但是当我输入两个学生的记录(允许的最大输入记录数)时,它不会打印它们。 这是程序。有人可以指出这个错误吗?谢谢。如何打印结构的成员?

#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

我不做家庭作品,但你很幸运。记住你不能输入比在结构字符串中声明的更长的时间 - 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; 
} 

,并在主要功能:

struct student *s = NULL; 
int numberofstudentds; 

numberofstudentds = read_students(s); 
+0

你建议删除整个while循环? – Gerhardh

+0

@Gerhardh我不建议 - 那些循环是我在生活中见过的最荒谬的东西 –

+0

是不是用包含'scanf'的3行代替完整'while循环包含3'for'循环的答案。 ? – Gerhardh