0

テキストファイルを解析および処理するためのプログラムを作成しようとしています。sscanfの実装に失敗した後、stringstreamを試すことにしました。

次のように、スペースで区切られたデータを含む文字列のベクトルがあります。

some_string another_string yet_another_string VARIABLE_STRING_NO_1 next_string

コードを書いたところ、期待される結果は次のようになります。

Counter: 4
Variable number 1 : VARIABLE_STRING_NO_1
Variable number 2 : VARIABLE_STRING_NO_2
Variable number 3 : VARIABLE_STRING_NO_3
Variable number 4 : VARIABLE_STRING_NO_4

しかし、代わりに私は得る:

Counter: 4
Variable number 1 : VARIABLE_STRING_NO_1
Variable number 2 : VARIABLE_STRING_NO_1
Variable number 3 : VARIABLE_STRING_NO_1
Variable number 4 : VARIABLE_STRING_NO_1

誰かが私を正しい方向に押してくれますか? (例: ベクターの代わりに他のコンテナーを使用する、メソッドを...に変更するなど)

また、VARIABLE_STRINGにスペースを挟んだ 2 つの部分文字列が含まれている場合はどうなるでしょうか。私のデータではそれが可能です。

サンプルコード:

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
    vector<string> vectorOfLines, vectorOfData;

    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_1 next_string");
    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_2 next_string");
    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_3 next_string");
    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_4 next_string");

    string data = "", trash = "";
    stringstream token;

    int counter = 0;

    for( int i = 0; i < (int)vectorOfLines.size(); i++ )
    {
        token << vectorOfLines.at(i);
        token >> trash >> trash >> trash >> data >> trash;
        vectorOfData.push_back(data);                       //  wrong method here?
        counter++;                                          //  counter to test if for iterates expected times
    }

    cout << "Counter: " << counter << endl;

    for( int i = 0; i < (int)vectorOfData.size(); i++ )
    {
        cout << "Variable number " << i + 1 << " : " << vectorOfData.at(i) << endl;
    }

    return 0;
}

初心者の質問で申し訳ありませんが、過去 5 日間さまざまなアプローチを試みた後、私は悪口を言い、学習を続けることを思いとどまらせてしまいました。
はい、私はC ++を初めて使用します。
私はPHPで同じプログラムを成功させました(それもまったくの初心者です)が、C ++ははるかに難しいようです。

4

1 に答える 1

4

個人を読んだ後、文字列ストリームをリセットしたい。見た目からすると、使用している文字列ストリームは失敗状態になります。この時点で、状態が取得されるまで、それ以上の入力を除外しませんclear()。また、読んだことが成功したことを常に確認する必要があります。つまり、ループの本体を次のように開始します。

token.clear();
token.str(vectorOfLines[i]);
if (token >> trash >> trash >> trash >> data >> trash) {
    process(data);
}
else {
    std::cerr << "failed to read '" << vectorOfLines[i] << "\n";
}

私も。を使用しstd::istringstreamます。

于 2012-09-24T22:03:30.597 に答える