0

重複の可能性:
C/C++ で構成ファイルを解析する

次のような C++ のテキスト ファイルがあります。

[layer]
type=background
data=
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,11,1,1,1,1,1,1,1,1,1,1,1,1,1,

ただし、同じテキストファイルに複数のレイヤーがあり、それぞれを異なる方法で構築する必要がありますが、レイヤーごとに「data =」に示されている値を取得する必要があります。

どうすればこれを達成できますか?私が試した方法は、それらをベクトルに格納することですが、すべてをベクトルに格納した後、それらの値をベクトルから抽出する解決策が思い浮かびません...

while(file >> line)
    {
        words.push_back(line);
    }

    if(find(words.begin(), words.end(), "[header]") != words.end())
    {
        for(int i = find(words.begin(), words.end(), "[header]"); words.at(i) != "\n"; i++)
        {
            word += words.at[i];
        }
    }
    cout << word << endl;
    file.close();
4

1 に答える 1

0

かなり簡単です。データは「data=」行の後に始まり、「[layer]」行で終わることがわかっているので、次のように検索します。

std::ifstream f("your_file");
std::string string;
while( f >> string && !f.eof() )
{
    if( string == "data=")//If we found the "data=" string, we know data begins next.
    {
        std::cout << std::endl << "new layer's data found" << std::endl;
        f >> string;//going to the next string (the actual data)
        //while we don't see the "[layer]" which indicates the end of data...
        while( string != "[layer]"  && !f.eof() )"[layer]"
        {
            std::cout << string;//...we output the data found
            f >> string;//and continue to the next string
        }
    }
}
于 2012-10-19T08:09:32.017 に答える