我在c上读取文件时遇到麻烦 [英] i have a trouble with the files's read on c

查看:71
本文介绍了我在c上读取文件时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从外部文件中读取矩阵,但我只是不知道,请帮助我,我得到了这段代码,并且输出结果不是我期望的输出结果>

解决方案

该代码甚至不应编译,更不用说按预期做任何事情了:)
第一件事是数组声明.这个:

int  adjacency [dimension][dimension];


应该给出一个错误(期望常量表达式"或类似的东西).如果您希望能够更改数组的大小,则可以使用define:

#define DIM 5
...
int adjacency [DIM][DIM];


或使用"new"运算符创建数组.

至于文件读取-您可能应该发布文件的内容-否则无法知道您要读取的内容.

我还建议在读取任何内容之前检查文件是否正确配置了...

if( f != NULL )


i wish to read a matrix from a external file but i just don''t know that , please help me , i got this code, and the output doesn''t is the output that i''m expected

<pre lang="cs">#include <stdio.h><br />
#include <stdlib.h><br />
<br />
/*<br />
 *<br />
 */<br />
<br />
<br />
<br />
int main(int argc, char** argv) {<br />
<br />
 FILE * f;<br />
 int i,j,dimension=5;<br />
 int  adjacency [dimension][dimension];<br />
f = fopen("adjacency.dat", "r");<br />
for(i = 0; i < dimension ; i++){<br />
    for(j = 0; j < dimension; j++){<br />
        fscanf(f, "%d", &adjacency[i][j]);<br />
        }<br />
    }<br />
fclose(f);<br />
<br />
printf("matriz de adyacencia \n");<br />
<br />
for (i=0;i<dimension;i++){<br />
    for(j=0;j<dimension;j++)<br />
        printf("%d",adjacency[i][j]);<br />
    printf("\n");<br />
}<br />
    return (EXIT_SUCCESS);<br />
}</pre><br />

解决方案

The code should not even compile let alone do anything as expected :)
The first thing is the array declaration. This:

int  adjacency [dimension][dimension];


should give an error (''expected constant expression'' or something like that). If you want to be able to change the size of the array you can either use a define:

#define DIM 5
...
int adjacency [DIM][DIM];


or use the ''new'' operator to create the array.

As for the file reading - you should probably post the contents of the file - otherwise there''s no way to know what you are trying to read.

I would also suggest checking if the file was oppened correctly before reading anything...

if( f != NULL )


这篇关于我在c上读取文件时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆