Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

c - How can we check if an input string is a valid double?

If I'm reading numbers of type double from stdin, how can I check if the numbers being read are in fact valid (that the numbers are in fact a double)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use strtod. Check if the result is zero and subsequently if endptr == nptr, according to the man page:

If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.

Something like this:

char input[50];
char * end;
double result = 0;

fgets(input, sizeof input, stdin);

errno = 0;

result = strtod(input, &end);

if(result == 0 && (errno != 0 || end == input)){
    fprintf(stderr, "Error: input is not a valid double
");
    exit(EXIT_FAILURE);
}

EDIT there seems to be a bit of a discrepancy between the standard and the man page. The man page says that endptr == nptr when no conversion is performed, while the standard seems to imply this isn't necessarily the case. Worse still it says that in case of no conversion errno may be set to EINVAL. Edited the example code to check errno as well.

Alternatively, sscanf could be used (preferred over scanf), in conjunction with fgets:

/* just fgetsed input */
if(sscanf(input, "%lf", &result) != 1){
    fprintf(stderr, "Error: input is not a valid double
");
    exit(EXIT_FAILURE);
}

Also, don't forget to check the return value of fgets for NULL, in case it failed!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

57.0k users

...