Search code examples
cinputsegmentation-faultdoublefgets

Trying to read double from user, getting segmentation fault


I'm writing a function to get input from the user where it only accepts a double value, if a wrong value is entered the user gets another chance to enter a double. I'm getting a segmentation fault whenever I input any numbers.

double ReadDouble(){
   double *ret;
   char buff[100];
   printf("Please enter a double ");
   while(fgets(buff, sizeof(buff), stdin) != 0){
      if(sscanf(buff, "%lf", ret) == 1){
         return *ret;
      }
      else{
         printf("Invalid input, please enter a double ");
      }
   }
   return EOF;
}

Solution

  • #include<stdlib.h>
    #include<stdio.h>
    double ReadDouble(){
       // you will return a double so you can directly declare it as a double and gives its address to the sscanf
       // if you declare it as double* you should allocate memory for it otherwise its not pointing to anything
       double ret;
       char buff[100];
       printf("Please enter a double ");
    
       while(fgets(buff, sizeof(buff), stdin) != 0){
         // passing the address of ret like this &ret to sscanf
          if(sscanf(buff, "%lf", &ret) == 1){
             return ret;
          }
          else{
             printf("Invalid input, please enter a double ");
          }
       }
       return EOF;
    }
    
    int main(){
    printf("%lf ",ReadDouble());
    }