0

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

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++;
    }
}
4

5 回答 5

2

关于什么:

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

如果您想要 a long:将字符保存在 a char[](而不是printf())中,然后在完成后将其转换为 a 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);

顺便说一句,你忘了p++什么时候is digit()是真的。

于 2014-01-20T09:04:37.130 回答
1

以下代码适用于我:

#include <stdio.h>
#include <string.h>

int main()
{

char *ptr = "3-423-62167-2";
char ISBN[20];  // should be either ISBN[] or char *ISBN for a string
char *p = ISBN; // declared this one here.. else should be p = ISBN

strcpy(ISBN, ptr);
printf("\nISBN Array: %s\n", ISBN);

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

}

已在评论中标记更正!

于 2014-01-20T09:16:43.057 回答
0

假设pchar *指针,您应该将代码更新为

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

保持其余代码不变。

于 2014-01-20T09:08:38.350 回答
0

使用不当strtol是不必要的;第二个参数不是输入,而是输出,即将其设置为最后一个解释字符。最重要的是,当您只需要一个要打印的字符时,为什么要将字符转换为 long 然后再将其转换回字符?

char ISBN[] = "3-423-62167-2";
char *p = ISBN;
while (*p)
{
    if (isdigit(*p))
        printf("%c", *p);
    ++p;
}

编辑:

要将整个字符串变成一个长字符串:

unsigned long long num = 0;
while (*p)
{
    if (isdigit(*p))
    {
        const char digit = *p - '0';
        num = (num * 10) + digit;
    }
    ++p;
}
于 2014-01-20T09:32:10.827 回答
0

我认为 OP 想要的是将带有连字符的字符串转换为长整数。此函数将字符串的十进制数字转换为长整数。连字符(在任何地方)都会被忽略,其他字符,包括空格,会导致阅读错误:

/*
 *      Return ISBN as long or -1L on format error
 */
long isbn(const char *str)
{
    long n = 0L;

    if (*str == '\0') return -1L;

    while (*str) {
        if (isdigit(*str)) {
            n = n * 10 + *str - '0';
        } else {
            if (*str != '-') return -1L;
        }
        str++;
    }

    return n;
}

请注意,在某些机器上 along的大小与 a 相同,int并且可能不够宽以存储数字 ISBN。

于 2014-01-20T09:57:28.430 回答