sscanf读取字符串中的字符串

时间:2013-09-10 02:14:32

标签: c string scanf

我有一个小问题,我似乎无法修复。说我有一个字符串,

buffer = "1 1 X ./simple E"

我想提取2个整数,2个字符和文件名,

sscanf(buffer, "%d %d %c %s %c, &a, &b, &c, d, &e);

printf("%d %d %c %s %c", a, b, c, d, e);

我没有得到我期望的回报。我得到“11 1 X(null)”。任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:0)

#include <cstdio>
#include <cstdlib>

int main() {
    char buffer[] = "1 1 X ./simple E", c, d[10], e;
    int a, b;

    //sscanf(buffer, "%d %d %c %*[./]%s %c", &a, &b, &c, d, &e); //To ignore "./"
    sscanf(buffer, "%d %d %c %s %c", &a, &b, &c, d, &e); //Don't ignore "./"
    printf("%d %d %c %s %c\n", a, b, c, d, e);
    return 0;
}

输出:

1 1 X ./simple E

答案 1 :(得分:0)

c和e可以是int或chars。请注意d [100]的溢出问题。

int a, b, c, e;
char d[100];
sscanf(buffer, "%d %d %c %s %c, &a, &b, &c, d, &e);

printf("%d %d %c %s %c", a, b, c, d, e);

答案 2 :(得分:0)

您要声明char *d,因为它没有有效的指向位置会失败。使用有足够空间的数组:

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

int main()
{
    int a, b;
    char c, e;
    char d[20];
    char buffer[] = "1 1 X ./simple E";
    sscanf(buffer, "%d %d %c %s %c", &a, &b, &c, d, &e);
    printf("%d %d %c %s %c", a, b, c, d, e);
}

输出:1 1 X ./simple E

答案 3 :(得分:0)

sscanf函数参数中不需要空格分隔符。

sscanf(buffer, "%d%d%c%s%c", &a, &b, &c, d, &e);
在读取缓冲区时,

%d是空白的,%c%s之间不应该有空格,因为它吞没了空格,使得缓冲区之间没有分隔符和字符串。

相关问题