I am new to this forum. I got a stuck in my work ... I have ASCII file with numerical values, and I need to read them and save them in a matrix of 2 dimensions?.... If anyone can help me please ....!!???
Read each line using getline() into a string. Use a stringstream to extract each item in the rows and then assign them to individual elements in the matrix.
after I learned C++ bit and I followed your suggestions. I wrote my code. It works but not like what I need, I cannot understand why. Since I need to read an ASCII numerical file and save data in matrix of two dimensions. Any more suggestions please.
The code is:
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <sstream>
usingnamespace std;
int main ()
{
string line;
int row,col;
float my_array[4][3];
ifstream pFile ("Data.txt");
if (pFile.is_open())
{
while(!pFile.eof())
{
getline(pFile, line);
stringstream ss(line);
col=0; row=0;
while(ss >> my_array[row][col])
col++;
row++;
}
pFile.close();
}
else cout << "Unable to open file";
for(int i=0;i<row;i++)
{for(int j=0;j<col;j++){
cout<<my_array[i][j]<<"\t";}
cout<<"\n";}
system("pause");
return 0;
}
and the example ascii file is:
1 2 3 4
12 23 45
32 12 21
34 56 78
98 76 54
So I want to get a matrix of two dimensions but I cannot see that in the output, where after I run the code above with example of ascii file I got the last row only and as following
I have solved the problem but I highly appreciate if there are more suggestions which make the code better in terms of programming. and help me to improve my programming skills.
The code is:
Hello
I have another challenge which I really do not know how to solve it.
The code above reads the ascii file, but now i want to read the FLT file. This is to difficult for me to figure out.
Please if the there is any suggestion would be appreciated.
The FLT file is a Float Grid format.
You have to find information about what that file is supposed to contain.
Quite likely there will be some sort of header and the array of floats.
see http://www.cplusplus.com/doc/tutorial/files/ (the part about binary files)
basically myfile >> my_float; becomes myfile.read((char*)&my_float, sizeof(float));
The EOF flag is not set until *after* the read fails. So you will process one line of bad data using that. It is much better to put your file read operation in the while clause if possible like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// getline() returns the stream. testing the stream with while returns error such as EOF.
while(getline(pFile, line))
{
// so here we know that the read was a success and that line has valid data
stringstream ss(line);
cout<<row<<"\n";
col=0;
cout<<col<<"\n";
while(ss >> my_array[row][col])
{
col++;
}
row++;
}
Thanks for your helps and suggestions. After I followed your suggestions and i got help from friend, I ended up with the following code which reads a flt file and store the data as a matrix of 2 D as follows:-