If you're trying to read from a file, use some function that will read from a file. Sitting at the beginning of a file and waiting for the end to come will not do much.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
ifstream infile("test_file.txt");
while ( getline(infile, line) )
{
cout << line << endl;
}
return 0;
}
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
I'd go with a vector of a vector of doubles. The vector of doubles per line, and the vector of these vectors for each line.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
A sample.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector < vector < double > > info;
ifstream file("file.txt");
string line;
while ( getline(file, line) )
{
vector < double > data;
double value;
istringstream iss(line);
while (iss >> value)
{
data.push_back(value);
}
info.push_back(data);
}
for ( vector < vector < double > > :: size_type i = 0, size = info.size(); i < size; ++i)
{
cout << "line " << i + 1 << ": ";
for ( vector < double > :: size_type j = 0, length = info[i].size(); j < length; ++j)
{
cout << info[i][j] << " ";
}
cout << endl;
}
return 0;
}
/* file.txt
1 2 3
4 5 6 7 8 9
10 11 12 13
14
15 16
*/
/* my output
line 1: 1 2 3
line 2: 4 5 6 7 8 9
line 3: 10 11 12 13
line 4: 14
line 5: 15 16
*/
There are probably better/easier ways to go about iterating through the loop, and I'm sure someone will let me know.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Is there a function in c++, like in pascal, so you can detect the end of a line? I know in pascal it would be like infile.eoln(), but that doesn't work in c++.
By the way, since we're posting at similar times, I thought I'd bring this up FWIW: http://www.eskimo.com/~scs/C-faq/q12.2.html
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
So all istringstream does is make each number on that one line ready to be stored into a variable?
It is used to do things like>> from a string instead of cin or an ifstream.
So the code I posted reads the whole line into a string, rather than going one value at a time (because both a newline and a space are whitespace characters, it might be tougher to distinguish using other means). Then it parses each double via the stringstream and >> operator.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314