0

我想从一个大文本文件中提取和分析数据。数据包含浮点数、整数和字。

我想这样做的方法是使用 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种,数据文件很大。

编辑:文件的一个例子是:

结果 时间 当前路径要求
PASS 04:31:05 14.3 Super_Duper_capacitor_413 -39.23
FAIL 04:31:45 13.2 Super_Duper_capacitor_413 -45.23
...

最终我想分析数据,但到目前为止我更关心正确的输入/阅读。

4

2 回答 2

2

您可以使用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-03T13:40:26.910 回答
1

对于第一个问题,您可以这样做:

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;
    }

}

至于第二个问题,您能否给我们更精确的数据类型以及您想对存储后的数据做什么?

于 2013-06-03T13:24:47.633 回答