读取文本文件到一个数组

读取文本文件到一个数组

本文介绍了读取文本文件到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很新的节目,并努力思考这一个星期的暑期项目后,我真的AP preciate一些帮助!

I'm really new to programming, and after thinking hard about this for a week for a summer project, I'd really appreciate some help!

我想在很长的文本文件,这仅仅是一个长字符串(注:不是一个实际的编程字符串)来读取信件,然后把每个字母到它发生在网格(该计划的目的最终是要解决一个单词搜索)到目前为止,我已经拿出了下面的程序,这似乎不能产生一个网格,而只是重印由以下pceded文本文件,$ p $:

I'm trying to read in a long text file, which is just a long string (NB: not an actual programming string) of letters, and then put each letter into its place in the grid (the aim of the program is ultimately to solve a wordsearch) so far I've come up with the program below, which doesn't seem to be producing a grid, but rather just reprints the text file, preceded by the following:

{\rtf1\ansi\ansicpg1252\cocoartf1138\cocoasubrtf510
{\fonttbl\f0\fmodern\fcharset0 Courier;}
{\colortbl;\red255\green255\blue255;}
\paperw11905\paperh16837\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\deftab720
\pard\pardeftab720

\f0\fs24 \cf0

这是我写的程序是这样的:

The program that I've written is this:

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>

int main()
{
    int i,j;
    char myarray[26][26],x;
    FILE *myfile;

    for (j=0; j<26; j++)                 //initialise array elements all to zero
    {
        for (i=0; i<26; i++)
        {
            myarray[i][j]=0;
        }
    }

    myfile=fopen("*redacted*","r");
    if (myfile!=NULL) //check file actually opened
    {
        for (i=0; i<26; i++)
        {
            for(j=0; j<26; j++)
            {
                fscanf(myfile,"%c",&x); //read the values in
                myarray[i][j]=x;
            }
        }
        // data is now in the array called myarray
        fclose(myfile);
    }

    else
    {
        printf("File not found");
    }

    for(i=0;i<26;i++)
    {
        for(j=0;j<26;j++)
        {
            printf("%c",myarray[i][j]);
        }
    }

}

感谢您对您可以提供任何帮助。

Thank you for any help you can offer

推荐答案

下面是C的美容:

您可以阅读单一操作的文件,并保存自己的循环:

You can read the file in a single operation, and save yourself the looping:

fread(myArray, sizeof(myArray), myfile)

您或许应该在你做这个数组初始化为全零,虽然:

You should probably initialize the array to all zeros before you do this, though:

char myArray[26][26] = { 0 };

或者用零填充它,如果你不初始化:

Or fill it with zeroes if you don't initialize it:

 memset(myArray, 0, sizeof(myArray));

此外,您可能希望在您的打印部分中的每个外层循环结束时打印一个换行符(\\ n):否则文件内容将显示为一个长,连续字符串

Also, you might want to print a newline ("\n") at the end of each outer loop in your printing section: otherwise the file contents will appear as one long, continuous string.

这篇关于读取文本文件到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:23