Search code examples
cfgetsinput-buffer

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


I tried to solve the problem* I face when I want to get user input inside a loop. edit *: problem is this -> clearing buffer to read next input.

is this error-prone?

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

Edit: This is the code i faced the error. without assignment to '\n' i got wrong loop coun and inputs. deleted those lines there is nothing wrong :/

#include <stdio.h>
#include <stdlib.h>
int main(){
        int numbers[100];
        int quant;
        char buffer[10];
        printf("how many numbers do i need to 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 was based on the memory overflow and 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 I enter more than 9 digits as an input (which i did accidentally), jumps to the next loop. If I clear buffer with while loop then nothing wrong happens. *buffer = '\n' useless, meaningles...


Solution

  • It's not "error-prone", but it is pointless.

    There is very rarely any point in "clearing" a buffer, and it's never well-defined what "clearing" means.

    Why do you feel the buffer needs to be cleared, when it's going to be overwritten by fget(), regardless of its contents? If the behavior is confusing, you should make sure fgets() succeeds before relying on the result.