0

所以我对为什么内置返回 0 感到困惑。从手册中它说,如果无法进行转换strtol,它将返回 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.

4

2 回答 2

1

你的代码

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

第二行有一些问题。

第一个参数&ptr应该只是ptr. 那是因为strtol想要一个简单的指向字符的指针作为它的第一个参数。因此,尽管与号在第一次调用strtol时是正确的,但在第二次调用中却不正确。

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

这又引入了另一个问题。在将指针移过逗号之前,您必须确保它确实指向逗号。如果没有,那就有问题了,你必须优雅地失败。由于您的函数返回一个指针,因此您应该返回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;
}
于 2014-10-16T05:09:05.907 回答
0

我想出的解决方案是在传递给 strtol 之前对字符串进行标记,但想象一下有一种更优雅的方式来执行此操作。

char *ptr =NULL;
char *ptrs =NULL;
const char *deli = ",";
char *denominations = strtok_r(val, deli, &ptrs);
char *counts = strtok_r(NULL, deli, &ptrs);

long int denomination = strtol(denominations, &ptr,10);
long int count = strtol( counts,NULL, 10);
于 2014-10-16T04:20:37.020 回答