[英]How to extract specific data from text file containing whitespace and newlines?
我想從一個大文本文件中提取和分析數據。 數據包含浮點數,整數和單詞。
我想到的方法是使用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
...
最終,我想分析數據,但是到目前為止,我更關心正確的輸入/讀取。
您可以使用std::stringstream
解析數據,並使其擔心跳過whitspace。 由於輸入行中的每個元素似乎都需要進行額外的處理,因此只需將它們解析為局部變量,並在完成所有后期處理后,將最終結果存儲到數據結構中。
#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;
對於第一個問題,您可以執行以下操作:
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;
}
}
關於第二個問題,您能否為我們提供關於數據類型的更精確的信息,對存儲后的數據您想做什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.