【发布时间】:2018-08-09 18:24:04
【问题描述】:
我想做什么: 使用 .txt 文件中的数据填充向量,该文件包含 3 列未知长度。每个向量的每一列。我也想在屏幕上打印矢量。
代码如下:
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 );
}
有什么问题:
- 我输入了“虚拟”变量,因为没有它我的输出是向量 充满了整个文件,但我不知道这是否是正确的解决方案。 现在我的输出是向量 u,其中填充了第一列的值。
- 如何用第二列和第三列的值填充其他向量?
- 如何处理列(文件)长度未知且可能为任何长度的事实?
- 有人能解释一下编译器如何知道何时停止创建和填充内部向量吗?变量 'col' 代表它,但它究竟是如何工作的?
【问题讨论】:
-
如果您提供输入和所需输出的示例,可能会有所帮助。
-
@mxdg 输入和输出是相同的,因为我应该在这个类中存储数据向量。我只是想确保我正确地填充它们。示例文件只有 3 列由空格分隔的双精度数。
标签: c++ file class c++11 stdvector