我想从一个大的文本文件中提取和分析数据。数据包含浮点数、整数和单词。
我想到的方法是使用std::getline()提取完整的行(直到换行符)。然后从前面提取的行中提取单个数据(提取到空格,然后重复)。
到目前为止,我有这样的想法:
int main( )
{
std::ifstream myfile;
myfile.open( "example.txt", std::ios::in );
if( !(myfile.is_open()) )
{ std::cout << "Error Opening File";
std::exit(0); }
std::string firstline;
while( myfile.good() )
{
std::getline( myfile, firstline);
std::cout<< "\n" << firstline <<"\n";
}
myfile.close();
return 0;
}
我有几个问题:
1)如何提取到空格?
2)存储数据的最佳方法是什么?大约有7-9种数据类型,而且数据文件很大。
编辑:该文件的示例如下:
结果时间当前路径要求
通过04:31:05 14.3 Super_Duper_capacitor_413 -39.23
失败04:31:45 13.2 Super_Duper_capacitor_413 -45.23
..。
最终,我想分析数据,但到目前为止,我更关心的是正确的输入/读取。
发布于 2013-06-03 21:40:27
您可以使用std::stringstream
来解析数据,并让它担心跳过空格。由于输入行中的每个元素似乎都需要额外的处理,因此只需将它们解析为局部变量,并在完成所有后处理之后,将最终结果存储到一个数据结构中。
#include <sstream>
#include <iomanip>
std::stringstream templine(firstline);
std::string passfail;
float floatvalue1;
std::string timestr;
std::string namestr;
float floatvalue2;
// split to two lines for readability
templine >> std::skipws; // no need to worry about whitespaces
templine >> passfail >> timestr >> floatvalue1 >> namestr >> floatvalue2;
如果您不需要或不想验证数据的格式是否正确,您可以直接将这些行解析为数据结构。
struct LineData
{
std::string passfail;
float floatvalue1;
int hour;
int minute;
int seconds;
std::string namestr;
float floatvalue2;
};
LineData a;
char sep;
// parse the pass/fail
templine >> a.passfail;
// parse time value
templine >> a.hour >> sep >> a.minute >> sep >> a.seconds;
// parse the rest of the data
templine >> a.timestr >> a.floatvalue1 >> a.namestr >> a.floatvalue2;
发布于 2013-06-03 21:24:48
对于第一个问题,您可以这样做:
while( myfile.good() )
{
std::getline( myfile, firstline);
std::cout<< "\n" << firstline <<"\n";
std::stringstream ss(firstline);
std::string word;
while (std::getline(ss,word,' '))
{
std::cout << "Word: " << word << std::endl;
}
}
至于第二个问题,你能给我们更多关于数据类型的精度吗,以及一旦存储数据,你想要做什么?
https://stackoverflow.com/questions/16897612
复制相似问题