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