2014-02-06 79 views
1

我需要使用升壓從文本文件的每一行獲得的數字:解析文本文件一行行與指定的分隔符

d$+$B$ 0.0 000 000 000 1.0 255 255 255 

類似:

0.0 000 000 000 1.0 255 255 255 

在Qt中,它是像這樣的那樣:

QString data = input->readLine(); 
o_name = data.section('$', 0, 2); 
QStringList dataLst = data.section('$', 3, 3).split(' ', QString::SkipEmptyParts); 
while(!dataLst.isEmpty()) 
//process 

什麼是boost中等效的alg?

到目前爲止,我只有這個:

boost::iostreams::basic_file<float>(filename, std::ios_base::in ); 
+0

爲「C++讀取文件分析變量」搜索StackOverflow。 –

回答

2

下面是使用升壓正則表達式很短的代碼段。我試圖用C++ 11獲得相同的工作,但似乎它不是由GCC 4.8.2尚不支持:GCC GNU

std::ifstream ifStreamObject("test", std::ifstream::in); 
    if (!ifStreamObject.is_open()) 
    { 
    // nothing to do 
    return -1; 
    } 
    std::string line; 
    boost::regex e("\\s+"); // split on whitespaces 
    boost::sregex_token_iterator j; 
    while (std::getline(ifStreamObject, line)) 
    { 
    boost::sregex_token_iterator i(line.begin(), line.end(), e, -1); 

    while(i!=j) 
    { 
     // display the tokens for now.. process the data here 
     cout << *i++ << endl; 
    } 
    } 

輸出:

d$+$B$ 
0.0 
000 
000 
000 
1.0 
255 
255 
255 
0

你可以使用升壓精神:

#include <boost/spirit/include/qi.hpp> 
#include <boost/spirit/include/qi_match.hpp> 
#include <fstream> 
using namespace boost::spirit::qi; 

int main() 
{ 
    std::string oname; 
    std::vector<double> numbers; 

    if (std::ifstream("input.txt") >> std::noskipws 
      >> match(*~char_('$') > '$') 
      >> match(*~char_('$') > '$') 
      >> match(*~char_('$') > '$', oname) 
      >> phrase_match(*double_, blank, numbers)) 
    { 
     std::cout << oname << ": parsed " << numbers.size() << " numbers: "; 
     for(auto d : numbers) 
      std::cout << d << " "; 
    } 
} 

它打印

B: parsed 8 numbers: 0 0 0 0 1 255 255 255 

爲您的示例行。看到它Live On Coliru

更新我只注意到你想整個 「d $ + $ B $」 被解析爲ONAME:

 >> match(raw [ repeat(3) [ *~char_('$') > '$' ] ], oname) 

或可替代只是

 >> match(*~char_('$') > char_('$'), oname) 
     >> match(*~char_('$') > char_('$'), oname) 
     >> match(*~char_('$') > char_('$'), oname) 

將連接成oname

+0

請問這是怎麼回事(std :: ifstream(「input.txt」)>> std :: noskipws >> match(*〜char _('$')>'$') >> match(* (char_('$')>'$',oname) >> phrase_match(* double_,blank,numbers))有效嗎?或一個鏈接到文檔,我找不到。特別是> phrase_match(* double_,blank,數字))什麼是params? – Oleksandra

+0

http://www.boost.org/doc/libs/1_55_0/libs/spirit/doc/html/spirit/qi/reference/parse_api/stream_api.html – sehe