您好我正在编写一个需要从文本文件中读取的程序,并且只接受整个文件的字母。它可能是
你好,我的名字是什么。我正在考虑写一个程序:“名字!”
我需要做的只是在字母中读取,所以我的输出将是:
hellomynameiswhateverimthinkingoftryingtowriteaprogramname
我有类似的东西:
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,我知道它应该比这简单得多。我只需要一个正确方向的*指针(双关语)!
答案 0 :(得分: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;
}
答案 1 :(得分:0)
从技术上讲,您可以使用fscanf直接忽略(*
禁止分配):
fscanf(in, "%*[^A-Za-z]%c", &c);
在这种情况下它并不是非常有用 - 内置格式字符串很慢。我只想使用fgetc
。