【问题标题】:sscanf reading multiple characterssscanf 读取多个字符
【发布时间】:2014-03-20 07:15:35
【问题描述】:

我正在尝试读取配置文件中给出的接口列表。

 char readList[3];

 memset(readList,'\0',sizeof(readList));

 fgets(linebuf, sizeof(linebuf),fp); //I get the file pointer(fp) without any error

 sscanf(linebuf, "List %s, %s, %s \n",
               &readList[0],
               &readList[1],
               &readList[2]);

假设配置文件的行是这样的 列出值1 值2 值3

我无法阅读此内容。有人可以告诉我这样做的正确语法吗?我在这里做错了什么。

【问题讨论】:

标签: c parsing scanf


【解决方案1】:

格式字符串中的%s 转换说明符读取非空白字符序列并存储在传递给sscanf 的相应参数所指向的缓冲区中。缓冲区必须足够大以存储输入字符串以及由sscanf 自动添加的终止空字节,否则它是未定义的行为。

char readList[3];

上述语句将readList 定义为3 字符数组。你需要的是一个足够大的字符数组来存储sscanf写的字符串。此外,sscanf 调用中的格式字符串"List %s, %s, %s \n" 意味着它必须完全匹配"List" 和字符串linebuf 中的两个逗号',否则sscanf 将由于匹配失败而失败。确保您的字符串 linebuf 被相应地格式化,否则我建议这样做。此外,您必须通过指定最大字段宽度来防止sscanf 超出其写入的缓冲区,否则将导致未定义的行为。最大字段宽度应比缓冲区大小小一以容纳终止空字节。

// assuming the max length of a string in linebuf is 40
// +1 for the terminating null byte which is added by sscanf 

char readList[3][40+1];  
fgets(linebuf, sizeof linebuf, fp);

// "%40s" means that sscanf will write at most 40 chars
// in the buffer and then append the null byte at the end.

sscanf(linebuf, 
       "%40s%40s%40s",
       readList[0],
       readList[1],
       readList[2]);

【讨论】:

    【解决方案2】:

    您的char readlist[3] 是一个由三个字符组成的数组。但是,您需要的是一个包含三个字符串的数组,例如 char readlist[3][MUCH]。然后,像阅读它们一样

    sscanf(linebuf, "list %s %s %s",
                    readList[0],
                    readList[1],
                    readList[2]);
    

    也许会成功。请注意,scanf 中的字母字符串需要逐个字符匹配(因此list,而不是List),格式字符串中的任何空格都是跳过字符串中所有空格直到下一个非空白字符。还要注意readList 参数中没有&,因为它们已经是指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 2016-08-14
      • 2012-06-06
      • 1970-01-01
      相关资源
      最近更新 更多