c - 从字符串中提取数字不起作用! C

标签 c string strtol

我会从 ISBN 字符串中删除“-”。 但是我的代码没有打印出我的值(value)。错在哪里?

char *ISBN[20];  //example: 3-423-62167-2
*p = ISBN;

strcpy(ISBN, ptr); //Copy from a Buffer
printf("\nISBN Array: %s", ISBN); //This works!

while(*p)
{
    if (isdigit(*p))
    {
        long val = strtol(p, &p, 10);
        printf("%ld\n", val);         //Do not show anything!
    }
    else
    {
        p++;
    }
}

最佳答案

关于:

for (char* p = ISBN; *p != '\0'; p++)
{
    if (isdigit(*p))
    {
        printf("%c", *p);
    }
}

如果你想要一个long:将字符保存在一个char[]中(而不是printf()),然后,当完成,将其转换为 long。您甚至可以使用 ISBN 数组进行就地转换:

int i = 0;
for (char* p = ISBN; *p != '\0'; p++)
{
    if (isdigit(*p))
    {
        ISBN[i++] = *p;
    }
}

ISBN[i] = '\0';

long isbn = strtol(ISBN, NULL, 10);

顺便说一句,当 is digit() 为真时,您忘记了 p++

关于c - 从字符串中提取数字不起作用! C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21229796/

相关文章:

c - 使用 strtok 对 C 中的字符串进行标记(包括数字作为分隔符)

string - Perl 中使用 "index()"与 RegEx 进行子字符串搜索的性能差异的原因是什么?

c - 为什么 strtol 返回错误值?

ubuntu - 如何使用 C/C++ 向 ttyACM0 设备写入命令并获取结果信息数据

c - 真的不检查close()的返回值: how serious,吗?

c - 互斥量和信号量实际上做了什么?

javascript - 表数据上的 G-mail 样式表单提交

string - flutter 中的拆分字符串

c - 为什么不能只检查 errno 是否等于 ERANGE?