2

我从 C 开始,我必须检查主函数的参数是否为双精度。我正在尝试使用 strtod,但这给我带来了一些麻烦。所以我的主要看起来像这样:

    int main (int argc, char* argv[]){
    if (!(strtod(argv[1], NULL)) /*trouble is with this line*/
       exit(EX_USAGE);
    else{
    /*some code*/
    }
    return(0);   
    }    

我已经使用 strtod 将 argv[1] 解析为双精度(没有问题),但问题是当 argv[1] 不是双精度时,因此显然无法解析。有任何想法吗?

4

4 回答 4

3

strtod()有第二个参数,它是一个指向 char 指针的指针。如果不是NULL,它会将停止转换的字符串中的地址写入该指针,因为其余的不是有效的浮点数表示。

如果整个字符串正确转换,那么显然该指针将指向字符串的末尾。转换应该是这样的,并进行了超出范围的检查:

char *endptr;
double result;

errno = 0;
result = strtod(string, &endptr);
if (errno == ERANGE) {
    /* value out of range */
}
if (*endptr != 0) {
    /* incomplete conversion */
}
于 2013-11-09T13:44:37.533 回答
2

strtod 用于将字符串(字符数组)转换为双精度。如果输入无效或输入有效零或输入是空格,则函数返回零。

于 2013-11-09T13:34:04.513 回答
0

This may be obvious, but you're not checking argc to ensure that you have a parameter to parse. You should be doing something like this:

int main (int argc, char* argv[]) {
    if (argc < 2) {
        exit(EX_USAGE);
    }
    double arg1 = strtod(argv[1], NULL);
    if (arg1==0 && strcmp(argv[1], "0")!=0) {
        exit(EX_USAGE);
    }
    /* some code */
}
于 2013-11-09T15:04:27.237 回答
0

你拥有男人所需要的一切:

姓名

   strtod, strtof, strtold - convert ASCII string to floating-point
   number

概要

   #include <stdlib.h>

   double strtod(const char *nptr, char **endptr);

描述

  The strtod(), strtof(), and strtold() functions convert the ini‐
  tial portion of the string pointed to by nptr to double, float,
  and long double representation, respectively.

返回值

   These functions return the converted value, if any.

   If endptr is not NULL, a pointer to the character after the last
   character used in the conversion is stored in the location ref‐
   erenced by endptr.

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

我发现最后一句话特别有趣。

于 2013-11-09T13:40:42.873 回答