fgets - is clearing the buffer by assigning char * buffer to '\n' while getting user input inside a loop in c wrong? -


i tried solve problem* face when want user input inside loop. edit *: problem -> clearing buffer read next input.

is error-prone?

 #include <stdio.h>       int main(){         char buffer[10];         while(1){           fgets(buffer,10,stdin);           // use buffer whatever need... then!           *buffer = '\n';         }     } 

edit: code faced error. without assignment '\n' got wrong loop coun , inputs. deleted lines there nothing wrong :/

#include <stdio.h> #include <stdlib.h> int main(){         int numbers[100];         int quant;         char buffer[10];         printf("how many numbers need ask? max = 99\n");         fgets(buffer,10,stdin);         quant = atoi(buffer);         *buffer = '\n';         printf("%d times enter numbers! max 9 digit long !\n",quant);         for(int i=0;i<quant;i++){                 printf("%d. number: ",i);                 fgets(buffer,10,stdin);                 numbers[i] = atoi(buffer);                 *buffer = '\n';          }          printf("numbers: \n");         for(int i=0;i<quant;i++){                 printf("%d ",numbers[i]);         } 

edit2: error based on memory overflow , how fgets handles inputs.

#include <stdio.h>  int main(){         int ch;         char buffer[10];          for(int i=0; i<3; i++){                  fgets(buffer,10,stdin);                 printf("%s -- %d. time\n",buffer,i+1);                 //while ((ch = getchar()) != '\n' && ch != eof);                 *buffer= '\n';         }         return 0; } 

if enter more 9 digits input (which did accidentally), jumps next loop. if clear buffer while loop nothing wrong happens. *buffer = '\n' useless, meaningles...

it's not "error-prone", pointless.

there point in "clearing" buffer, , it's never well-defined "clearing" means.

why feel buffer needs cleared, when it's going overwritten fget(), regardless of contents? if behavior confusing, should make sure fgets() succeeds before relying on result.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -