使用fscanf()进行格式化输入

时间:2014-10-17 06:28:10

标签: c scanf

我正在尝试从文本文件中读取非数字单词,可以用逗号,点,冒号或引号或其中某些组合来区分,如#34;。我到目前为止尝试的代码是读取非数字字 正确,但留下分隔符。我使用fscanf()吧?

int ReadWords(FILE* fp, char *words[])
{
    int i=0;
    char temp[50],tmp[50]; // assuming the words cannot be too long
    while (fscanf(fp,"%s%*[,.\":]",temp)==1) //ignore punctuation
    {
        if (isNumeric(temp))
            continue;
        printf("%s\n",temp);
        words[i] = strdup(temp);
        i++;
    }
    fclose(fp);
    // The result of this function is the number of words in the file
    return i;
}

我得到像

这样的输出
emergency,"
"an
unknown
car
entered,

我需要像

emergency
an
unknown
car
entered

2 个答案:

答案 0 :(得分:1)

%s格式扫描“单词”,即连续非空格的块。这包括标点符号。

您想要扫描非数字字词,即仅扫描字母字符。对于这些字符,您可以使用%[...]格式为标点符号进行操作:

while (fscanf(fp, "%49[a-zA-Z]%*[^a-zA-Z]", temp) == 1) ...

注意事项:

  • 减号定义括号中的字符范围,除非它是第一个或最后一个字符,因此%[a-zA-Z]扫描不重音的拉丁字母。
  • 我在格式中添加了最大字长49,这样就不会溢出字符缓冲区。
  • 我把除字母以外的任何东西当作标点符号。这是一个简单的假设,但它将您的输入整齐地划分为字母/标点符号序列。您可以使用插入符^作为括号内的第一个字母来否定要包含的字母。
  • 您可能应首先对标点符号进行(可能为空)扫描,以便真正的扫描以字母开头。

答案 1 :(得分:0)

原因是你在使用ignore子句之前就已经消耗了标点符号。

尝试:"%[^,.\":]%*[,.\":]"

相关问题