无法在C语言中使用sscanf()函数解析字符数组

4

我想获取一个非常大的数字(超过unsigned long long int),所以我将其作为字符串获取,然后逐位将其转换为整数并使用。

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

int main() 
{ 
    char m[100];
    int x;
    scanf("%s",m);
    for(int i=0; i<strlen(m); i++){
        sscanf(m[i],"%d",&x);
        printf("%d",x);
    }

    return 0; 
}

然而,在编译时,它显示:

警告:传递整数时,‘sscanf’的参数1会产生指针而不设置

注意:期望为‘const char * restrict’,但参数类型为‘char’

当我运行程序时,它会给我一个 Segmentation fault (core dumped) 错误。

我还尝试了更简单的代码来查找问题:

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

int main() 
{ 
    char m[5];
    char n;
    int x;
    scanf("%s",m);
    n = m[1];
    sscanf(n,"%d",&x);  
    return 0; 
}

但是什么都没有改变。


%d并不表示“数字”,而是表示“有符号十进制整数”。关于错误本身,sscanf需要一个const char *(即一个字符串),但你却只提供了一个单独的字符。 - kaylum
2
使用m只有四个字符加上一个感谢,"非常长"是一个令人震惊的误称。你不能安全地使用%d来处理非常长的数字字符串;溢出时的行为是未定义的。 - Jonathan Leffler
1
sscanf(m[i],"%d",&x); 是错误的。你应该使用 x = m[i] - '0';。而且你的输入字符串对于一个大数来说太小了。 - Jean-François Fabre
2个回答

4

scanf不能应用于字符。一旦你有了字符,只需通过将'0'作为字符减去来将数字转换为整数:

for(int i=0; i<strlen(m); i++){
    x = m[i] - '0';   // line to change
    printf("%d",x);
}

此外,为了确保缓冲区不会溢出,使用100字节是不错的选择,但你可能想在scanf函数中设置相应的限制并检查返回代码:
if (scanf("%99s",m) == 1) {

2
使用sscanf将字符字符串的一个单个数字转换为整数是错误的方法。要做到这一点,你只需要从该数字中减去字符'0'的表示的(整数)值即可。像这样:
#include <stdio.h>
#include <string.h>

int main()
{
    char m[50]; // As pointed out, a 4-digit number isn't really very long, so let's make it bigger
    int x;
    scanf("%49s", m); // Limit the input to the length of the buffer!
    for (size_t i = 0; i < strlen(m); i++) { // The "strlen" function return "size_t"
        x = m[i] - '0'; // The characters `0` thru `9` are GUARANTEED to be sequential!
        printf("%d", x);
    }
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接