#include <stdio.h>
#include <ctype.h>
int main()
{
FILE *ptr_file;
char buff [100];
char word [100];
int i=0;
int j=0;
int g=0;
char a;
ptr_file = fopen ("input.txt", "r");
if (!ptr_file)
printf("File read error");
while(fscanf(ptr_file, "%s ", buff, &a) != EOF)
{
if (isalpha(buff[i]))
{
word[j] = buff[i];
j++;
i++;
}
else
{
i++;
}
printf("%s \n", word);
}
fclose(ptr_file);
return 0;
}
嗨,我正在尝试编写一个函数,该函数使用 fscanf() 逐行读取文件,将文本读入缓冲区字符数组,然后在读入时逐字符检查以查看是否读入的字符是字母字符,即字母,如果是,则将其添加到另一个名为 word 的数组中。
我有两个增量器,如果字符是字母顺序的,那么两个增量器都会增量,否则只有 buff 上的增量器增量,这允许我跳过非字母字符。
在我看来,这在逻辑上应该有效,但是当我尝试打印单词数组时,我得到的输出非常奇怪。 原始文件读取
Line 1 rgargarg.
Line 2 agragargarrrrrrr.
Line 3 rrrrrrrrrrrr.
Line 4 agragarga.
gOOdbye.
函数后的输出应该是
Line rgargarg
Line agragargarrrrrrr
Line rrrrrrrrrrrr
Line agragarga
gOOdbye
实际输出是-
L
L
La
Lae
Lae
Laea
Laear
Laearg
Laeargr
Laeargrr�
Laeargrrr
Laeargrrrr
Laeargrrrr
我已经尝试让它工作一段时间了,只是不知道如何让它按预期工作。
最佳答案
您实际上需要使用循环扫描输入字符串。
请参阅下面的固定代码以及注释。
请注意,代码做了两个假设:输入字符串以 null 结尾。输入字符串和单词字符串不能超过100个字符(考虑空终止)。
后者非常危险,因为如果不遵守会导致缓冲区溢出和内存损坏。
#include <stdio.h>
#include <ctype.h>
int main()
{
FILE *ptr_file;
char buff [100];
char word [100];
int i=0;
int j=0;
int g=0;
char a;
ptr_file = fopen ("input.txt", "r");
if (!ptr_file)
printf("File read error");
while(fscanf(ptr_file, "%s ", buff, &a) != EOF)
{
i=0;
j=0;
word[0]=0;
while(buff[i]!=0) // assuming the lines you're reading are null terminated string
{
if (isalpha(buff[i]))
{
word[j] = buff[i];
j++;
i++;
}
else
{
i++;
}
}
word[j]=0; // this ensures word is a null terminated string
printf("%s \n", word);
}
fclose(ptr_file);
return 0;
}
关于c - 如何从文件读入并从缓冲区输出到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20031145/