我对编程很陌生,在为一个夏季项目做了一周的努力之后,我真的很感激一些帮助!
我正在尝试读取一个长文本文件,它只是一个长字符串(NB:不是一个实际的编程字符串)的字母,然后将每个字母放入网格中的位置(该程序的目标最终是解决一个wordsearch)到目前为止,我已经提出了下面的程序,它似乎没有生成网格,而只是重新打印文本文件,前面有以下内容:
{\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
Run Code Online (Sandbox Code Playgroud)
我写的程序是这样的:
#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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您提供的任何帮助
这就是C的美妙之处:
您可以通过一次操作读取文件,并节省循环:
就像是
fread(myArray, sizeof(myArray), myfile)
Run Code Online (Sandbox Code Playgroud)
不过,在执行此操作之前,您可能应该将数组初始化为全零:
char myArray[26][26] = { 0 };
Run Code Online (Sandbox Code Playgroud)
或者如果不初始化它,则用零填充它:
memset(myArray, 0, sizeof(myArray));
Run Code Online (Sandbox Code Playgroud)
另外,您可能希望在打印部分的每个外循环末尾打印换行符(“\n”):否则文件内容将显示为一个长的连续字符串。
| 归档时间: |
|
| 查看次数: |
10948 次 |
| 最近记录: |