gpt4 book ai didi

c - 字符串长度有限的 strtod

转载 作者:太空狗 更新时间:2023-10-29 15:17:59 26 4
gpt4 key购买 nike

如果我想将 char 数组中的前 3 个字符解析为 double,忽略后面的字符,我真的需要这样做吗?

int main() {    const char a[] = "1.23";    char *b = malloc(sizeof(char) * 4);    memcpy(b, a, sizeof(char) * 3);    b[3] = '\0';    printf("%f\n", strtod(b, NULL)); // Prints 1.20000, which is what I want    free(b);}

难道没有像 strtod 这样的函数允许您指定它应该搜索数字的最大字符串长度吗?

编辑:我希望它打印1.2(它目前这样做),不是 1.23!

最佳答案

虽然 strtod() 不允许您限制字符串长度,但您可以使用具有最大字段宽度sscanf()以及对消耗的字符数的可选检查,如下所示:

#include <stdio.h>

double parseDouble(const char *str){
double val = 0;
int numCharsRead;

// Handle errors by setting or returning an error flag.
if(sscanf(str, "%3lf%n", &val, &numCharsRead) != 1){
puts("Failed to parse double!");
}
else if(numCharsRead != 3){
puts("Read less than three characters!");
}

return val;
}

int main(){
printf("%lf\n", parseDouble("1.3")); // 1.300000
printf("%lf\n", parseDouble("1.5999")); // 1.500000
printf("%lf\n", parseDouble(".391")); // 0.390000
printf("%lf\n", parseDouble(".3")); // Read less than three characters!\n0.300000
return 0;
}

sscanf(str, "%3lf%n", &val, &numCharsRead 是重要的部分:您指定最大宽度为 3,这意味着 sscanf()将为该特定字段读取最多 3 个字符,并将解析结束时消耗的字符数存储在 numCharsRead 中。然后,如果您可以检查该值关心每次只读 3 个字符;如果您不介意 3 个或更少,您可以只使用 sscanf(str, "%3lf", &val)。作为引用,这里是宽度的文档说明符:

An optional decimal integer which specifies the maximum field width. Reading of characters stops either when this maximum is reached or when a nonmatching character is found, whichever happens first. Most conversions discard ini‐ tial white space characters (the exceptions are noted below), and these discarded characters don't count toward the maximum field width. String input conversions store a terminating null byte ('\0') to mark the end of the input; the maximum field width does not include this terminator.

关于c - 字符串长度有限的 strtod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16412840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com