所以我很困惑为什么内置的 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/