1

我想int从 C 中的string( char*) 解析一个。我正在为嵌入式 linux 编写一个 linux 内核模块。我正在尝试使用simple_strtolfound here

我在理想情况下解析的令牌将是数字。我遇到的问题"0"是有效输入。如果无法解析值(错误),则strtol返回。0所以这意味着以下代码:

char* token = "should_fail";

char **endptr;
char value = simple_strtol(token, endptr, 10); // 10 is the base to convert to
if (!**endptr){
    printf("failed!");
} else {
    printf(value);
}

char* token = "0"; // should pass
char **endptr;
char value = simple_strtol(token, endptr, 10); // 10 is the base to convert to
if (!**endptr){
    printf("failed!");
} else {
    printf(value);
}

在两种情况下都打印出来0,而在第一种情况下它应该失败。我正在尝试使用该*endptr参数来检查转换是否成功,但它不起作用。根据我的研究,*endptr是“指向已解析字符串末尾的指针将放置在此处”。而且我相信如果转换失败,指针将指向任何内容,因此我可以识别该失败。

有谁知道我如何"0"正确解析并获得返回值,0同时仍然识别失败的解析,而不是让它返回0

4

1 回答 1

3

You should not create a pointer-to-pointer variable for endptr. Instead declare a single pointer, and pass the address of that with the unary & operator:

char *endptr;

simple_strtol(token, &endptr, 10);

if (endptr == NULL) ...

I didn't read the manual page but basically copied what the OP had used. Froom the manual page:

If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of str is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

This means that if strtol (or your alternative if it's working as specified) returns 0 and endptr == token then the string was invalid.

So the check should be

if (value == 0 && endptr == token)
{
    /* String is not a valid number */
}
于 2012-11-21T04:07:04.283 回答