2013-02-02 22 views
0

我正在使用解析器來解析網格文件(已轉換爲字符串)以製作簡單的2D圖形。這裏的文件是如何格式化的例子(有這樣的多個網格,使該文件):使用從指定位置或標籤開始的字符串流標記字符串

# left ladder pole 
begin_mesh 
dimension 2 2 
begin_vertices 
-0.3 0.85 
-0.2 0.85 
-0.3 -0.85 
-0.2 -0.85 
end_vertices 
end_mesh 

的「#」表示註釋行的開始,你可以看到begin_mesh和begin_vertices關鍵字,顯示x和y值的開始。

所以基本上我想解析和標記'begin_vertices'和'end_vertices'之間的空格之間的頂點x和y值(數字)。有沒有使用stringstream(或可能的其他字符串函數)來做到這一點?我有更多使用字符串函數的經驗,但由於空格和數字長度不一樣,所以我遇到了麻煩。

任何幫助表示讚賞,謝謝!

+0

[你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

回答

0

如果我正確理解你想達到的目標,那麼是的,你可以使用istringstream從字符串讀取輸入,就像從文件中讀取一樣。以下程序顯示了你將如何去分析你所提供的輸入:

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

using namespace std; 

struct point 
{ 
    double x = 0; 
    double y = 0; 
    friend istream& operator >> (istream& is, point& p) 
    { 
     is >> p.x; 
     is >> p.y; 
     return is; 
    } 
}; 

template<typename InputStream> 
void parse_vertices(InputStream& is, vector<point>& v) 
{ 
    point p; 
    while (is >> p) 
    { 
     v.push_back(p); 
    } 
} 

上述功能是通用的,這意味着它同樣適用與字符串流或文件流。假設你想從一個字符串讀取你的輸入,這是你將如何調用它:

int main() 
{ 
    string s = 
     R"(-0.3 0.85 
     -0.2 0.85 
     -0.3 -0.85 
     -0.2 -0.85 
     )"; 

    istringstream is(s); 

    vector<point> vertices; 
    parse_vertices(is, vertices); 

    for (point const& p : vertices) 
    { 
     cout << p.x << " " << p.y << endl; 
    } 
} 

希望這會有所幫助。