What i want to do: Fill vectors with data from .txt file which contains 3 columns of unknown length. Each column for each vector. I also want to print vectors on screen.
Here is the code:
using namespace std;
class Equation
{
vector < vector <double> > u;
vector< vector <double> > alfa;
vector < vector <double> > f;
string fileName;
public:
Equation(string fileName);
};
Equation::Equation(string fileName)
{
cout<< "Give name of the file:" << endl;
cin >> fileName;
fstream plik;
plik.open( fileName.c_str(), ios::in | ios::out );
if( plik.good() == true )
{
cout << "file is open" << endl;
bool first = false;
if (plik)
{
string line;
while (getline(plik,line))
{
istringstream split(line);
double value;
int col = 0;
char sep;
double dummy;
while (split >> value >> dummy )
{
if(!first)
{
// Each new value read on line 1 should create a new inner vector
u.push_back(vector<double>(value));
}
u[col].push_back(value);
++col;
// read past the separator
split >> sep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
first = true;
}
}
// printing content of vector u:
for (const auto & vec : u)
{
for (const auto elem : vec)
cout << elem << ' ';
cout << '\n';
}
// now vector alfa:
bool second = false;
if (plik)
{
string sline; //as second line
while (getline(plik,sline))
{
istringstream ssplit(sline); // as second split
double svalue;
int scol = 0;
char ssep;
while ( ssplit >> svalue)
{
if(!second)
{
// Each new value read on line 1 should create a new inner vector
alfa.push_back(vector<double>());
}
alfa[scol].push_back(svalue);
++scol;
// read past the separator
ssplit>>ssep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
second = true;
}
}
for (const auto & svec : alfa)
{
for (const auto selem : svec)
cout << "wektor u: " << selem << ' ';
cout << '\n';
}
}
else
cout << "error" << endl;
}
int main()
{
Equation("");
getch();
return( 0 );
}
What are the problems:
- I puted 'dummy' variable since without it my output was vector filled with whole file, but i don't know if thats proper solution. Now my output is vector u filled with values from first column.
- How to fill other vectors with values from second and third column?
- How to handle the fact that length of the columns (file) is unknown and may be any?
- Would someone explain how compiler knows when to stop creating and filling inner vectors? Variable 'col' stands for that, but how exactly does it work?