我想做什么: 使用.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 );
}
有什么问题:
答案 0 :(得分:1)
如果我说对了,这是一个合法的.txt文件的示例:
info.txt
125.5 1648.2 16325.151
156464.1631 1231.156 0.1
1 231 54832
15236.15 12 0.6414787
在cpp中,您可以通过代码结构中带有fit变量的文件结构来读取文件。尝试以下代码:
struct DataReader {
vector<double> a_vec;
vector<double> b_vec;
vector<double> c_vec;
};
int main(){
ifstream file("/path/to/your/file/info.txt");
DataReader dr;
double a, b, c;
while (!file.eof()) {
file >> a >> b >> c;
dr.a_vec.push_back(a);
dr.b_vec.push_back(b);
dr.c_vec.push_back(c);
}
for (size_t i = 0; i < dr.a_vec.size(); i++) {
cout << dr.a_vec[i] << " " << dr.b_vec[i] << " " << dr.c_vec[i] << endl;
}
return 0;
}