尝试从用户读取双精度字,出现细分错误

时间:2019-01-27 20:55:18

标签: c input segmentation-fault double fgets

我正在编写一个从用户那里获取输入的函数,该函数仅接受双精度值,如果输入了错误的值,则用户将有另一个输入双精度值的机会。每当输入任何数字时,我都会遇到分段错误。

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;
}

2 个答案:

答案 0 :(得分:4)

#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());
}

答案 1 :(得分:3)

请勿声明ret指针。而是将其声明为变量,然后通过scanf将其地址移交给&ret

double ret;

if (sscanf(buff, "%lf", &ret) == 1) {
    return ret;
}