#include<iostream>
#include <string>
#include <vector>
#include <sstream> //字符串转换
#include <fstream>
using namespace std;
int main()
{
ifstream fin("test.txt");
string line;
vector<double> location_1, location_2, location_3;
if (fin)
{
while (getline(fin, line)) //按行读取到line_info中
{
if (line.size() == 0)
{
break; //循环体内手动的进行空行的判断
}
//cout << "line:" << line << endl;
istringstream sin(line); //create string input object
vector<string> Waypoints;
string info;
while (getline(sin, info, ' '))
{
//cout << "info:" << info << endl;
Waypoints.push_back(info);
}
string x1_str = Waypoints[0];
string x2_str = Waypoints[1];
string x3_str = Waypoints[2];
// cout<< "x_str" << x_str << endl;
// cout<< "y_str" << y_str << endl;
double x1, x2, x3;
stringstream sx1, sx2, sx3; //transform string to double
sx1 << x1_str;
sx2<< x2_str;
sx3 << x3_str;
sx1 >> x1;
sx2 >> x2;
sx3>> x3;
location_1.push_back(x1);
location_2.push_back(x2);
location_3.push_back(x3);
}
}
else
{
cout << "no such file" << endl;;
}
fin.close();
for (int j = 0; j < location_1.size(); j++)
{
cout << "location_1[" << j << "]: " << location_1[j] << " ";
cout << "location_2[" << j << "]: " << location_2[j] <<" " ;
cout << "location_3[" << j << "]: " << location_3[j] <<" " ;
cout << endl;
}
return 0;
}
处理istream流额时候,getline()的返回值是这样的:
只要可以读到文件内容(包括空行),返回值就一直是True. 如果读取失败,那么会抛出相对应的异常。