#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()逐行读取文件,将文本读取到缓冲区char数组中,然后在读取字符时逐字符检查该字符,以查看是否读取了字符in是字母字符,即字母,如果是的话,则将其添加到另一个称为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/

10-11 22:49
查看更多