Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取包含负数的矩阵并存储在数组中。C_C_File - Fatal编程技术网

读取包含负数的矩阵并存储在数组中。C

读取包含负数的矩阵并存储在数组中。C,c,file,C,File,我需要读取一个包含矩阵的文件。问题是,如果矩阵也包含负数怎么办 2 -20 1 5 -4 -312 10 4 -3 假设该文件包含此项。如何读取并存储在int数组中?语言是C。感谢您的帮助。负数与正数一样处理。政府明确表示: dDecimal integer任意数量的十进制数字(0-9),可选择前面带有符号(+或-)。 () 因此,如果在fscanf中使用%d,则无需对负数执行任何特殊操作 #include <stdio.h> #include <std

我需要读取一个包含矩阵的文件。问题是,如果矩阵也包含负数怎么办

2  -20   1
5   -4  -312
10   4    -3

假设该文件包含此项。如何读取并存储在
int
数组中?语言是C。感谢您的帮助。

负数与正数一样处理。政府明确表示:

d
Decimal integer任意数量的十进制数字(0-9),可选择前面带有符号(+或-)。
()

因此,如果在
fscanf
中使用
%d
,则无需对负数执行任何特殊操作

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

int main(void)
{
    int matrix[3][3];
    int row,col;
    FILE *read_file;

    read_file = fopen ("matrix.txt", "r");
    for (row=0; row<3; row++)
    {
        for (col=0; col<3; col++)
        {
            if (fscanf (read_file, "%d", &matrix[row][col]) < 1)
            {
                printf ("unexpected end of file or other error\n");
                exit(-1);
            }
        }
    }
    fclose (read_file);

    for (row=0; row<3; row++)
    {
        for (col=0; col<3; col++)
        {
            printf ("%4d ", matrix[row][col]);
        }
        printf ("\n");
    }

   return 0;
}

2-20 1是第一排5-4-312是第二排10 4-3是第三排首先感谢你的帮助。但是你上面写的代码不起作用。当我尝试时,所有的矩阵数组元素都是0。很抱歉我发现了这个问题,谢谢你的帮助。你说得对:)@AybarTaş:它有效——正如你在“结果”部分所看到的。但是我必须发明我自己的输入文件,因为你没有在你的问题中提供一个。如果我要使用的矩阵是动态二维的?有什么变化吗?
   2  -20    1 
   5   -4 -312 
  10    4   -3