Friday, July 31, 2009

How to read numbers into a 2D array from a text file in C++?

Hi,





How do I read numbers from a text file into an integer 2D array?





The numbers in the text file are arranged in 10 rows by 10 columns. The 2D array is declared as int data[10][10];


The numbers in the file are arranged like this:


1100110011


1000010011


0111011101


.....


.... and so on....





Below is a code snippet I wrote which doesnt work:





ifstream inClientFile("Test.txt",ios::in); int k = 0; int i = 0;


while(!inClientFile.eof())


{


for(j =0; j %26lt; 10;j++)


inClientFile%26gt;%26gt;correlDataset[k][j];


k++;


}





So how do I read the numbers from the textfile into a 2D array? Any help will be appreciated!

How to read numbers into a 2D array from a text file in C++?
I think this code will work.





char ch;


int a[10][10];


int i=0, j=0;





ifstream file("Test.txt")


while(!file.eof())


{ ch = file.get(); // all text is as character so read it into a char


if(ch='\r') // if there is a line change


i++; // change row in array


else


a[i][j++] = ch - 48;//otherwise get the integer value from char.


}





Contact me if there is still some problem


No comments:

Post a Comment