2014-09-20 130 views
0

我試圖解析文本文件。解析格式化文本文件

的格式是:

  1. 6空格
  2. 空間+下劃線+串
  3. 逗號+下劃線+串
  4. 逗號+下劃線+串

這裏是一個例子:" house1 _rst1,_ab,_aaaa"

此代碼工作:

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 

int main() { 
    ifstream infile("test.txt"); 
    string line; 
    while (getline(infile, line)) { 
     string house, param1, param2, param3; 
     size_t posP1, posP2, posP3; 

     // trim leading whitespaces 
     while (isspace(line.at(0))) 
      line = line.substr(1,line.length() - 1); 

     posP1 = line.find(" _"); 
     house = line.substr(0, posP1); 

     posP2 = line.find(",_", posP1 + 2); 
     param1 = line.substr(posP1 + 2, posP2 - posP1 - 2); 

     posP3 = line.find(",_", posP2 + 2); 
     param2 = line.substr(posP2 + 2, posP3 - posP2 - 2); 

     param3 = line.substr(posP3 + 2, line.length() - 2); 

     cout << house << " : " << param1 << ", " << param2 + ", " << param3 << endl; 
    } 
    return 0; 
} 

我得到house1 : rst1, ab, aaaa,但我想,以提高使用類似stackoverflow.com/a/3555952/3029422的代碼,但我不知道如何將它應用到我的情況,當我嘗試:

ifstream infile("test.txt"); 
string line; 
while (getline(infile, line)) { 
    string house, param1, param2, param3; 

istringstream iss(line); 
    if (!(iss >> house >> param1 >> param2 >> param3)) 
     cout << "not the expected format" << endl; 
    else 
     cout << house << " : " << param1 << ", " << param2 + ", " << param3 << endl; 

我得到not the expected format

我怎樣才能從文件中讀取每一行直接插入變量?我看起來更乾淨,更容易閱讀。

+0

默認分析僅適用於以空格(空白)分隔的情況。你有用逗號隔開的字段,它會爲你指定一些更多的工作。 – woolstar 2014-09-20 01:23:14

回答

1

我發現使用streams而不是string處理這樣的解析行很容易。我經常使用std::istringstream將我讀取的行轉換爲解析流。

也許這個例子代碼可能對你有用嗎?

#include <string> 
#include <sstream> 
#include <iostream> 

int main() 
{ 
    std::string line = " house1 _rst1,_ab,_aaaa"; 

    std::string house, param1, param2, param3, skip; 

    std::istringstream iss(line); 

    iss >> house; 
    std::getline(iss, skip, '_'); 
    std::getline(iss, param1, ','); 
    std::getline(iss, skip, '_'); 
    std::getline(iss, param2, ','); 
    std::getline(iss, skip, '_'); 
    std::getline(iss, param3); 

    std::cout << house << " : " << param1 << ", " << param2 + ", " << param3 << '\n'; 
} 

編輯:

你也可以連接流調用在一起,形成一個全encompasing行分析器,而像這樣:

#include <fstream> 
#include <string> 
#include <iostream> 

int main() 
{ 
    std::ifstream infile("test.txt"); 

    std::string house, param1, param2, param3; 

    // this uses ignore() to skip over the '_' characters and std::getline() 
    // to read up to the ',' delimeters. 
    while(std::getline(std::getline(std::getline((infile >> house >> std::ws).ignore() 
     , param1, ',').ignore(), param2, ',').ignore(), param3)) 
    { 
     std::cout << house << " : " << param1 << ", " << param2 + ", " << param3 << '\n'; 
    } 
} 

但是,這可能是難以閱讀;○ )