【问题标题】:Using fscanf for a txt file and ignoring everything but letters将 fscanf 用于 txt 文件并忽略除字母之外的所有内容
【发布时间】:2014-10-03 23:01:26
【问题描述】:

您好,我正在编写一个程序,它需要从文本文件中读取,并且只接收整个文件的字母。可能是这样的

你好,我叫什么名字。我正在考虑尝试编写一个程序:“name!”

我需要做的只是阅读字母,所以我的输出将是:

hellomyname 是我想写的程序名

我有这样的东西:

while (fscanf(ifp2, "%c", &file[i]) != EOF) //scans until end of file
    {
        for (i = 0; i < 10000; i++) //loops a possible 10000, file could possibly be that big
        {
            //printf("Got inside while loop [%d]\n", i); //this just lets me see the loop
            if (fscanf(ifp2, "%c ", &file[i]) == 0) //im trying to see how i can ignore some data
            {
                fscanf(ifp2, "%c ", &file[i]); //scans in the character
            }

        }
    }

for (i = 0; i < 10000; i++)//prints the array of characters. 
{
    if(file[i] == NULL)//keeps from printing uninitialized parts of array
    {
        break;
    }
    else
    {
        if (counter % 80 == 0) //makes it print 80 characters per line
        {
            printf("\n");
        }
        printf("%c", file[i]);//prints the character
        counter++;
    }

}

我知道我可以以某种方式使用 fscanf,而且我知道它应该比这简单得多。我只需要一个指向正确方向的*指针(双关语)!

【问题讨论】:

  • 每次调用fscanf 都会占用另一个角色。一次读一个,然后立即检查。
  • 我应该寻找什么?如果 fscanf(ifp2, "%c ", &file[i]) == ':' 然后什么都不做,应该是什么?
  • 你知道你可以做到这一切,只需使用适当的配置(伪)while fgetc { if (isalpha) fputc } 循环,对吧?
  • 不,我将如何使用它?我以前从未这样做过。

标签: c file scanf


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>

int main()
{
  FILE *fp;
  char c;
  fp = fopen("sample.txt", "r");
  if (fp == NULL) {
         printf("Couldn't open file  for reading.\n");
         exit(0);
      }
  while (fscanf(fp, "%c",&c) != EOF)
    {
      if (isalpha(c))
    printf("%c", c);
    }
  printf("\n");
  return 0;
}

【讨论】:

  • 谢谢!!!我可以用这个!现在我将把值放入数组中:)
  • 你知道我怎样才能把 c 放入我的数组文件中吗?
  • 您的意思是要在另一个文件中打印输出?
【解决方案2】:

从技术上讲,您可以使用 fscanf 直接忽略(* 抑制分配):

fscanf(in, "%*[^A-Za-z]%c", &c);

在这种情况下它并不是非常有用 - 解释格式字符串很慢。我只会使用fgetc。

【讨论】:

  • 当我做 while (fscanf(ifp2, "%c", &amp;file[i]) != EOF) { for (i = 0; i &lt; 10000; i++) { fscanf(ifp2, "%*[^A-Za-z]%c", &amp;file[i]); } } 它只是崩溃:C
  • @Enigma ...你为什么要这样嵌套循环?
猜你喜欢
  • 2018-09-17
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 2010-11-11
  • 2010-11-02
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
相关资源
最近更新 更多