|
-
February 10th, 2007, 06:45 AM
#1
How to read from a text file of rows and columns?
Hi,
How do I read from a text file with 1000 rows and 24 columns into an array?
The values are negative decimal point numbers with several spaces in between the values.
An example of the text file is:
-4.848335 -4.108572 -1.760031 -1.358524 -1.551027 -1.743531 -2.414542 -0.572010 0.266755 2.860050 3.553062 -0.382257 0.539009 0.929516 -1.262272 0.596760 1.204521 1.595028 0.486759 -1.652779
...............
-
February 10th, 2007, 03:44 PM
#2
Re: How to read from a text file of rows and columns?
You can use operator >> to read the individual elements. So, if the
number of rows/columns are fixed, you can read in as follows:
Code:
#include <fstream>
using namespace std;
int main()
{
double array[1000][24];
ifstream in("in.txt");
for (int i=0; i<1000; ++i)
{
for (int j=0; j<24; ++j)
{
in >> array[i][j];
}
}
return 0;
}
Here is a more general function for reading in any number of rows/columns.
In addition, the number of columns in each row do not have to be the
same. Also, it can read into more general 2D structures, such as
a list< deque<double> >.
Code:
#include <fstream>
#include <vector>
#include <sstream>
#include <string>
#include <list>
#include <deque>
#include <iostream>
using namespace std;
template <typename Container>
void Read_2D_array(Container & v , const char * fname)
{
using namespace std;
v.clear();
string line;
typedef typename Container::value_type V1D;
V1D v1d;
typename V1D::value_type t;
ifstream in(fname);
while (getline(in,line))
{
v1d.clear();
stringstream ss(line);
while (ss >> t) v1d.push_back(t);
v.push_back(v1d);
}
}
int main()
{
using namespace std;
vector < vector<double> > V;
Read_2D_array(V , "doubles.txt");
// print out what was read in
for (size_t i=0; i<V.size(); ++i)
{
for (size_t j=0; j<V[i].size(); ++j)
{
cout << V[i][j] << " ";
}
cout << "\n";
}
// other examples
list< deque<int> > L;
Read_2D_array(L , "ints.txt");
deque< vector<string> > D;
Read_2D_array(D , "strings.txt");
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|