c - Replace the usage of gets with getchar -


i have homework assignment , used gets. professor said should using getchar instead.

what difference?

how change code use getchar? can't seem right.

code:

#include <stdio.h> #include <string.h> #include <strings.h> #define storage 255  int main() {   int c;   char s[storage];    for(;;) {     (void) printf("n=%d, s=[%s]\n", c = getword(s), s);     if (c == -1) break;   } }  int getword(char *w) {   char str[255];   int = 0;   int charcount = 0;    printf("enter sentence:\n");   //user input   gets(str);    for(i = 0; str[i] != '\0' && str[i] !=eof; i++){     if(str[i] != ' '){       charcount++;     } else {       str[i] = '\0'; //terminate str       = -1; //idk doing?       break;      //break out of for-loop     }   }    printf("your string: '%s' contains %d of letters\n", str, charcount); //output   strcpy(w, str);    //    return charcount;   return strlen(w); //not sure should returning.... both work } 

gets() was supposed string input , store supplied argument. however, due lack of preliminary validation on input length, vulnerable buffer overflow.

a better choice fgets().

however, coming usage of getchar() part, reads 1 char @ time. basically, have keep reading standard input 1 one, using loop, until reach newline (or eof) marks end of expected input.

as read character (with optional validation), can keep on storing them in str that, when input loop ends, have input string ready in str.

don't forget null terminate str, in case.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -