c - 如何让 scanf 继续使用空扫描集

标签 c unicode scanf

我目前正在尝试解析 UnicodeData.txt使用此格式:ftp://ftp.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.html但是,我遇到了一个问题,当我尝试阅读时,说出如下一行。

something;123D;;LINE TABULATION;

我尝试通过如下代码从字段中获取数据。问题是 fields[3] 没有被填充,scanf 返回 2。in 是当前行。

char fields[4][256];
sscanf(in, "%[^;];%[^;];%[^;];%[^;];%[^;];",
    fields[0], fields[1], fields[2], fields[3]);

我知道这是 scanf() 的正确实现,但是除了我自己的 scanf() 之外,有没有办法让它工作?

最佳答案

scanf 不处理“空”字段。所以你必须自己解析它。

解决方案如下:

  • 快,因为它使用 strchr 而不是相当慢的 sscanf
  • 灵活,因为它可以检测任意数量的字段,直到给定的最大值。

parse 函数从输入的 str 中提取字段,以分号分隔。四个分号给出五个字段,其中一些或全部可以为空。没有规定转义分号。

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

static int parse(char *str, char *out[], int max_num) {
    int num = 0;
    out[num++] = str;
    while (num < max_num && str && (str = strchr(str, ';'))) {
        *str = 0;           // nul-terminate previous field
        out[num++] = ++str; // save start of next field
    }
    return num;
}

int main(void) {
    char test[] = "something;123D;;LINE TABULATION;";
    char *field[99];
    int num = parse(test, field, 99);
    int i;
    for (i = 0; i < num; i++)
        printf("[%s]", field[i]);
    printf("\n");
    return 0;
}

这个测试程序的输出是:

[something][123D][][LINE TABULATION][]

更新:一个稍微短一点的版本,不需要额外的数组来存储每个子字符串的开头,是:

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

static int replaceSemicolonsWithNuls(char *p) {
    int num = 0;
    while ((p = strchr(p, ';'))) {
        *p++ = 0;
        num++; 
    }
    return num;
}

int main(void) {
    char test[] = "something;123D;;LINE TABULATION;";
    int num = replaceSemicolonsWithNuls(test);
    int i;
    char *p = test;
    for (i = 0; i < num; i++, p += strlen(p) + 1)
        printf("[%s]", p);
    printf("\n");
    return 0;
}

关于c - 如何让 scanf 继续使用空扫描集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22974628/

相关文章:

c - 如何在没有确定输入量的情况下使用 scanf

c - 为什么 [0-9A-Z^%] 后不应该有 s 或 c 之类的类型说明符?

mysql - "AddDefaultCharset utf-8"指定的 Apache utf-8 字符集是否是完整的 utf-8?

unicode - 有没有真正的 unicode 替代品?

C幂函数和scanf

c - `if (variable % 2 == 0)`时程序崩溃

c - 错误 C2440 : 'function' : cannot convert from 'node *' to 'node'

c - C 代码有问题

c - C 中的垂直翻转位图不起作用

unicode - Dummy 的 Unicode 指南