简体   繁体   English

使用fscanf将文件中的单词存储在数组中

[英]Using fscanf to store words from file in an array

I am trying to write a program for some classwork that reads in a file using fscanf, and then stores each word into an array with one word in each element. 我正在尝试编写一些用于使用fscanf读取文件的类作业的程序,然后将每个单词存储到一个数组中,每个元素中都包含一个单词。 Then I need to print each element of the array out on to a new line on the console. 然后,我需要将数组的每个元素打印到控制台上的新行中。

The getty.txt file has the Gettysburg address in it with appropriate spacing, punctuation, and is multiline. getty.txt文件中的葛底斯堡地址带有适当的间距,标点符号,并且是多行的。

What I think is happening is that the entire text is being stored in the first element of the array, but I am not 100% sure as I am still learning to debug and write in C. 我认为正在发生的事情是,整个文本都存储在数组的第一个元素中,但是我还不能100%地确定,因为我仍在学习使用C进行调试和编写。

Any advice as to what I am doing wrong would be great! 关于我在做什么错的任何建议都很好! I currently only seem to be getting the last word and some extra characters. 我目前似乎只得到最后一个字和一些额外的字符。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void readFile();
void writeFile(char* buffer, int bufferlen);
FILE *fpread;
FILE *fpwrite;

char filebuffer[1000];
int filebufferlen = 0;


int main(int argc, char *argv[]) {
    fpwrite = fopen("csis.txt", "w");

    readFile();
    writeFile(filebuffer, filebufferlen);

    fclose(fpwrite);
    return 0;
}

void readFile() {
    char c;
    filebufferlen = 0;

    if(!(fpread = fopen("getty.txt", "r"))){
        printf("File %s could not be opened. \n", "getty.txt");
        fprintf(fpwrite,"File %s could not be opened. \n",     "getty.txt");
    exit(1);
}

    while (!feof(fpread)) {
        fscanf(fpread, "%s", filebuffer);
        filebufferlen++;
    }
}


void  writeFile(char* filebuffer, int filebufferlen) {
    for (int i = 0; i < filebufferlen; ++i){
            printf("%c\n", filebuffer[i]);
    }       
}

After fixing the compile problems: 解决编译问题后:

the code does not contain any code nor data declarations to contain an array of 'words.' 该代码不包含任何代码或数据声明来包含“单词”数组。 So naturally, nothing but the last word is actually saved so it can be printed out. 因此,自然而然地,除了最后一个单词,什么都没有保存,因此可以打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM