[英]Using fscanf for a txt file and ignoring everything but letters
您好,我正在編寫一個需要從文本文件讀取的程序,並且只接受整個文件的字母。 可能是
您好,我叫什么名字。 我正在考慮嘗試編寫一個程序:“名稱!”
我需要做的只是讀字母,所以我的輸出是:
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,我知道它應該比這簡單得多。 我只需要向正確的方向添加一個*指針(雙關語)即可!
#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;
}
從技術上講,您可以使用fscanf直接忽略( *
取消分配):
fscanf(in, "%*[^A-Za-z]%c", &c);
在這種情況下,它不是非常有用-解釋格式的字符串很慢。 我只會使用fgetc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.