Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
Dear All,
I have some matrix written in text file and I want to store these matrices in 2 d integer array.I have tried to read it using getline but it reads the whole line.How can I read from specific location in text file.Size of matrices is also unknown.

My text file is like

Matrix A is

2 4 8 10 2
1 2 5 7 11

Matrix B is
1 2 3
11 25 27

It would be really nice,if anyone body can help me.

Regards,
Ishtiaq
Posted
Comments
Sergey Alexandrovich Kryukov 12-Jun-11 21:10pm    
If a size of matrix is unknown, can number of rows also change? If so, what defines the number of rows? Not clear. Otherwise, it's a trivial problem.
--SA
smishtiaqhussain 13-Jun-11 13:02pm    
thanks for reply.......its done
Sandeep Mewara 13-Jun-11 10:45am    
Any effort?
smishtiaqhussain 13-Jun-11 13:01pm    
thanks ......its done just now.

1 solution

As the name of getline() implies, it's used for reading entire lines at a time... if you want to read an integer at a time... try this:

ifstream file;
file.open( "C:\\TestFile.txt");
int test[5] = {0};

for( int i=0; i<5; i++)
    file >> test[i];

file.close();

Now for this code I just read in 5 numbers into a flat 1D array, but that should give you the right idea of what you need to do. If you need it to be dynamic, you'll have to allocate the array dynamically:
int *test; //declare as pointer
test = new int[size]; //Allocate after you figure out the size

//After you're done with it, deallocate
delete [] test;
 
Share this answer
 
Comments
Niklas L 13-Jun-11 3:54am    
Good explanation. 5.
smishtiaqhussain 13-Jun-11 13:02pm    
thanks a lot for ur help......its done
Albert Holguin 13-Jun-11 13:04pm    
sure :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900