Date: Wed, 11 Dec 1996 13:36:27 GMT From: kvhk AT ivs4 DOT barco DOT com (Koen Van Herck) Message-Id: <9612111336.AA09140@ivs4.> To: jesusfreak44 AT juno DOT com Cc: djgpp AT delorie DOT com In-Reply-To: <19961209.194348.6911.2.jesusfreak44@juno.com> Subject: reading strings Reply-To: Koen DOT VanHerck AT barco DOT com I have fixed up the program. The problem was that scanf stops reading a string when it sees a space. So you can't enter a name with a space in it. I have made a function, `getstring', which reads a string from stdin. I tried to make it fail-safe, i.e., EOF and long input lines are handled correctly. Just have a look. ---begin program--- #include struct entry { char fname[20]; char lname[20]; char phone[10]; }; struct entry list[4]; int i; /* Read a string from stdin */ /* Return 0 on error, buffer on success */ char *getstring(char *buf, int maxlen) { char c, *end; if (!fgets(buf, maxlen, stdin)) return 0; /* return 0 on error */ end = buf+strlen(buf)-1; /* pointer to last character */ if (*end == '\n') { *end = '\0'; /* replace newline with NULL */ } else { /* skip rest of input line */ while ((c = getc(stdin)) != EOF && c != '\n'); } return buf; } int main() { for (i=0; i<4; i++) { printf("\nEnter first name: "); getstring(list[i].fname, 20); printf("Enter last name: "); getstring(list[i].lname, 20); printf("Enter phone in XXX-XXXX format: "); getstring(list[i].phone, 10); } printf("\n\n"); for (i=0;i<4;i++) { printf("Name: %s %s",list[i].fname,list[i].lname); printf("\tPhone: %s\n", list[i].phone); } return 0; } ---- Koen Van Herck Electronic Design Engineer E-mail: Koen DOT VanHerck AT barco DOT com BBBB AAA RRRR CCC OOO B A R C O V I S U A L S Y S T E M S B B A A R R C O O A division of Barco Projection Systems B BB A AAA R RR C OO O OO B B A A R R C O O Noordlaan 5 Tel +32 (0)56 36 85 71 BBBB A A R R CCC OOO B-8520 Kuurne Fax +32 (0)56 36 83 55