#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
int main(){
std::string fileName = "my_file.txt" ;
std::ifstream fstr( fileName.c_str() ) ; // 打开文件,建立数据流
double val ;
int i = 1 ;
while( std::getline(fstr, lineStr ) ) // 读取一行
{
sstr << lineStr ; // 将读取的数据压入到 sstr
sstr >> seg_path >> val ; // 使用sringsream 拆分数据
std::cout << "line " << i << " " << seg_path << " " << val << std::endl;
i++ ;
sstr.clear() ; // this is important. 注意将stringsream对象清空,否则一直为第一行
}
fstr.close() ; //关闭数据流
return 1;
#include<sstream>
#include<string>
#include<fstream>
int main(){
std::string fileName = "my_file.txt" ;
std::ifstream fstr( fileName.c_str() ) ; // 打开文件,建立数据流
std::string lineStr ;
std::stringstream sstr ;
std::string seg_path;double val ;
int i = 1 ;
while( std::getline(fstr, lineStr ) ) // 读取一行
{
sstr << lineStr ; // 将读取的数据压入到 sstr
sstr >> seg_path >> val ; // 使用sringsream 拆分数据
std::cout << "line " << i << " " << seg_path << " " << val << std::endl;
i++ ;
sstr.clear() ; // this is important. 注意将stringsream对象清空,否则一直为第一行
}
fstr.close() ; //关闭数据流
return 1;
}
--------------------------------------
注意: sstr >> seg_path >> val ; // 应将数据全部逐个读出,否则下一个循环中接着读的。