1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student
{
char firstName[21];
char lastName[51];
char studentCode[8];
int flag;
};
int readInput(char *, int len);
#define MAXNUM 200
int main()
{
struct Student students[MAXNUM];
int count = 0;
while (count < MAXNUM && readInput(students[count].firstName, 21))
{
readInput(students[count].lastName, 51);
int ok = readInput(students[count].studentCode, 8);
if (!ok)
{
printf ("Error reading student input\n");
printf("%20s, %50s %7s\n ------ error ---- \n", students[count].firstName,
students[count].lastName, students[count].studentCode );
break;
}
count++; // ------------ important --------------------
// if (feof(stdin))
// {
// printf ("End of file reading student input\n");
// break;
// }
}
for (int i=0; i<count; i++)
{
printf("%20s, %50s %7s\n", students[i].firstName, students[i].lastName, students[i].studentCode );
}
puts("\n -- Done --\n");
return 0;
}
int readInput(char * field, int len)
{
int ch;
static char buf[1024];
char * ok = fgets(buf, len, stdin); // allow for newline at end
int n = strlen(buf);
if (buf[n-1] == '\n') // remove newline if present
buf[n-1] = '\0';
else
do {
ch = fgetc(stdin);
} while (ch != '\n' && ch != EOF); // ignore until newline found
strncpy(field, buf, len);
// if (n > len) // add missing null terminator if required
// field[len-1] = 0;
return (ok != NULL);
}
|