c++读取三行txt,每一行分别存入相应的指定vector
C++ 的一个基础问题。。
读取data.txt,文件里面含有三行数字,每行数字个数不限,怎么将他们分别读出存入到的三个vector,v1,v2,v3中?。。原谅我吧,新手一枚 c++ vector read?in
[解决办法]
是这个意思不?
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
vector<double> v1, v2, v3;
string line;
int lineno = 0;
char *stop;
ifstream infile("data.txt");
while (getline(infile, line))
{
switch (lineno) {
case 0: v1.push_back(strtod(line.c_str(), &stop)); break;
case 1: v2.push_back(strtod(line.c_str(), &stop)); break;
case 2: v3.push_back(strtod(line.c_str(), &stop)); break;
}
lineno++;
}
// result = v1 + v2
vector<double> result(v1.size(), 0 );
transform(v1.begin(), v1.end(), v2.begin(), result.begin(), plus<double>());
// print:
// v1
// +
// v2
// =
// result
//
vector<double>::const_iterator it;
for (it = v1.begin(); it != v1.end(); it++)
cout << *it << endl;
cout << "+" << endl;
for (it = v2.begin(); it != v2.end(); it++)
cout << *it << endl;
cout << "=" << endl;
for (it = result.begin(); it != result.end(); it++)
cout << *it << endl;
return 0;
}