Last week i put on air my very very simple doubt (i think it should be that way!!!).
So, i'm trying to copy a matrix of integers (0 and 1s) in text format (matrix.txt) to a matrix (bidimensional array on C++).
Can anyone give me some suggestions please
if this is the case, then let us assume that your text file contains only those numbers, and they are separated by space. so it would look something like
1 2 3 4 4
2 3 4 5 5
5 5 5 5 5
the code to read it is
Code:
int x[3][5];
ifstream infile;
infile.open("mymatrix.txt");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
infile>>x[i][j];
}
}
if you are using Visual C++ .NET, you also need to include
using namespace std;
right after all your includes.
another problem is that your input to the program are not used. they are supposed to indicate the rows and columns of the matrix, however, in your for loops, you have hard-coded the size to be 3x5. you need to replace them with lines and cols.
First i have to thanks emanresu and gorshing for your suggestions.
Following some desperation as i think every day i understand less of C i have tried other way and, for the some kind of aim i built the following progr (with dynamic arrays). Once again probs occorred. What might be the errors?
#include <stdio.h>
void main()
{
int col, row, i, j;
int **arr;
FILE *fin;
fin=fopen("test.txt","r");
printf("number of cols:\n");
scanf("%d\n\n",&col);
printf("number of rows:\n");
scanf("%d\n\n",&row);
arr=new int*[row];
for(i=0;i<row;i++)
{
arr[i]=new int[col];
for(j=0;j<col,j+)
{
fscanf(fin,"%d \n,&arr[i][j]);
}
}
fclose(fin);
printf("%d \n",arr[1][1]);
}
Compiling...
test.c
C: \MyProjects\test\test.c(13) : error C2065: 'new' : undeclared identifier
C:\ MyProjects\test\test.c(13) : warning C4047: '=' : 'int ** ' differs in levels of indirection from 'int '
C:\ MyProjects\test\test.c(13) : error C2143: syntax error : missing ';' before 'type'
C:\ MyProjects\test\test.c(16) : warning C4047: '=' : 'int *' differs in levels of indirection from 'int '
C:\MyProjects\test\test.c(16) : error C2143: syntax error : missing ';' before 'type'
C:\ MyProjects\test\test.c(17) : error C2059: syntax error : ')'
C:\ MyProjects\test\test.c(19) : error C2001: newline in constant
C:\ MyProjects\test\test.c(25) : fatal error C1004: unexpected end of file found
Error executing cl.exe.
test.exe - 6 error(s), 2 warning(s)
Diogo André Alagador
MSc. Applied Math on Biological Sciences
Lisbon, Portugal