c - strtol帮助为什么它返回0

标签 c struct strtol

所以我很困惑为什么内置的 strtol 返回 0。手册中说,如果无法进行转换,它将返回 0。尽管我也应该正确转换。这就是函数。

struct coin * addCoins(char *val){
    char *ptr =NULL;
    long int denomination = strtol(val, &ptr,10);
    long int count = strtol( &ptr,NULL, 10);
        printf("%d",count);
    struct coin *k;
    k = malloc(sizeof(struct coin));
    k->denom = denomination;
    k->count = count;
    return k;
}

这会返回硬币面额的长整数,以及硬币的数量,然后将其存储在硬币类型的结构中。其中具有以下typedef

/* Each coin in the coins array will have a denomination (20 cents, 
 * 50 cents, etc) and a count - how many of that coin do we have on hand
 */
struct coin
{
    enum denomination denom;
    unsigned count;
};

正在读入的文件格式如下。 第一列是面额,第二列是计数

1000,3
500,4
200,20
100,30
50,5
20,3
10,40
5,20

分隔符是逗号。我们特别告诉我们要使用 strtol,否则我会使用 strtok_r

最佳答案

你的代码

long int denomination = strtol(val, &ptr,10);
long int count = strtol( &ptr,NULL, 10);

第二行有一些问题。

第一个参数&ptr应该只是ptr。这是因为 strtol 需要一个简单的指向 char 的指针作为其第一个参数。因此,尽管 & 符号在第一次调用 strtol 中是正确的,但在第二次调用中就不正确了。

第二个问题是从 strtol 返回的 endptr 指向不属于第一个数字的第一个字符。换句话说,它指向逗号。您可以将指针移过逗号。

这就引入了另一个问题。在将指针移过逗号之前,您必须确保它确实指向逗号。如果没有,那么就有问题了,你必须优雅地失败。由于您的函数返回一个指针,因此您应该返回 NULL 来指示发生了错误。

因此,你的函数应该是

struct coin * addCoins(char *val)
{
    char *ptr;
    long int denomination = strtol( val, &ptr, 10 );
    if ( ptr == val || *ptr != ',' )   // verify that we found the comma
        return NULL;
    ptr++;                             // advance the pointer past the comma

    char *endptr;
    long int count = strtol( ptr, &endptr, 10 );
    if ( endptr == ptr || *endptr != '\0' )   // verify that the second conversion succeeded
        return NULL;

    struct coin *k;
    k = malloc(sizeof(struct coin));
    k->denom = denomination;
    k->count = count;
    return k;
}

关于c - strtol帮助为什么它返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26396136/

相关文章:

c - 在 openSUSE 上用 C 语言的 mpi 编译 hello world 程序时出错

php - 使用 sizeof() 将代码从 C++ 移植到 PHP

c++ - 在 C++ 中调用另一个函数时,编译器在参数中查找已删除的构造函数

C 使用 Strtol 将字符串解析为两个整数

使用 strtok 的 C 标记化打印出意外的值并阻碍了我的 strtol 验证

rust - 如何在不消耗迭代器int rust的情况下获取元素(在rust中重写strtol的问题)

c - 函数未返回预期值

c - 使用 union 变量分配两个值

对将字符传递给函数参数时何时使用 int 类型或 char 类型感到困惑?

c - C中的数据封装