【问题标题】:C - How can I take words from file without numbers, special characters(, . ? &)?C - 如何从文件中获取没有数字、特殊字符(、。?&)的单词?
【发布时间】:2015-05-14 16:14:50
【问题描述】:

我想从文件中取词。我被发送到数组。我用 fscanf 做到了这一点。但是,它需要数字、字符(、. % & # !?)和其他东西。如何控制这个语句?

int main(void) 
{       
  char path[100];
  printf("Please, enter path of file: "); scanf("%s",&path);
  FILE *dosya;
  char kelime[1000][50];
  int i=0;

  if((dosya = fopen(path,"r")) != NULL)
  {
    while(!feof (dosya))
    {
        fscanf(dosya,"%s",&kelime[i]);
        i++;
    }
  }
  else{printf("Not Found File !");}
  fclose(dosya);
}

【问题讨论】:

  • 不要使用while (!feof(...)),它在大多数情况下不会按预期工作。而是使用例如while (fscanf(dosya, "%s", &kelime[i]) == 1).
  • 对于您的问题,您可能会发现this scanf (and family) reference 很有用,尤其是关于"%[" 格式的部分。
  • 顺便说一句 fclose 应该在 if ... != NULL 检查内。关闭NULL 时,某些(大多数?)系统会崩溃。
  • Not Found File ! 是所谓的无用错误消息。 if((dosya = fopen(path,"r")) == NULL ) { perror(path);}

标签: c file word scanf


【解决方案1】:

使用"%[]"区分字母和非字母。

#define NWORDS (1000)
char kelime[NWORDS][50];

size_t i;
for (i=0; i<NWORDS; i++) {
  // Toss ("*" indicates do not save) characters that are not ("^" indicates `not`) letters.
  // Ignore return value
  fscanf(dosya, "%*[^A-Za-z]");

  // Read letters
  // Expect only a return value of 1:Success or EOF:no more file to read
  // Be sure to limit number of characters read: 49
  if (fscanf(dosya, "%49[A-Za-z]", kelime[i]) != 1) break;
}

// do something with the `i` words

【讨论】:

    【解决方案2】:

    您可以使用fgetc()

    char str[1000];
    while((ch=fgetc(fname))!=EOF)
    {
            // Write your code here;
            if((ch>='0' && ch<='9') || (ch<'a' && ch>'z') || (ch<'A' && ch>'Z'))
                  continue;
            str[i++]=ch;
    }
    str[i]='\0';
    

    当您使用fscanf() 时,无法解析该语句。所以你必须

    1. 逐字符检查

    2. 如果不是特殊字符或数字,则添加到字符串中

    【讨论】:

    • 您没有说明这如何帮助 OP 排除他正在避免的字符。
    • @DavidHoelzer 现在可以了吗?
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多