0

外部ファイルから数値を読み取り、int のベクトルに格納する必要があります。Howard Hinnant と wilhelmtell のおかげで、今ではこれを行うことができます。

追加機能をコードに組み込む方法を見つけようとしてきましたが、ストリームに関する知識を使い果たしたので、アドバイスをいただければ幸いです。

多くのデータセットを含むファイルを処理できるようにしたい。ファイルから特定のデータのみをベクターに抽出することはできますか? ファイルのさまざまな部分からのデータを含むいくつかのベクトルを作成したいと考えています。私はオンラインで検索しましたが、これに関する言及は見当たりませんでした。

これがコードと、データを取得するファイルの例です (「テスト」と呼びましょう)。


編集: CashCow のアドバイスに基づいてコードを編集しました。これで、データ ファイルからブロックを取得できます。しかし、必要なブロックを取得する方法がわかりません。コードをそのまま実行すると、要素 2、5、8 を含むベクトルが得られます (これは私が望んでいるものではありません)。vectorTwo (作成した例では 4,5,6) を取得するために、while ステートメントの周りにこれを追加してみました。

if( line == "vectorTwo" )
{
      // The while statement and its contents
}

それは動かなかった。コードを実行しても結果は得られませんでした (ただし、コンパイルされました)。誰が問題が何であるかを見ることができますか? このステートメントを使用して、必要なデータ ブロックのヘッダーを検索できると考えました。


//サンプルファイルの内容はこちら

vectorOne // 1 つのベクトルのデータのサブセットの識別子

'1' '2' '3'

vectorTwo // この 1 つのベクトルを取得するにはどうすればよいでしょうか? または他の 1 つのベクトルですか?

「4」「5」「6」

vectorThree // 別のベクトルのデータのサブセットの識別子

'7' '8' '9'

// コード: '\'' 文字は行区切り文字です。最初の ' まではすべて無視され、次の ' まではすべて数値の一部です。これは、ロジックが失敗する (ファイルの終わり) まで続きます。代わりに、データブロックの最後で停止するにはどうすればよいですか?

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

int main()
{
    std::string line;
std::string block;         // Edited, from CashCow
    const std::string fileName = "test.dat";  

    std::ifstream theStream( fileName.c_str() ); 

    if( ! theStream )
          std::cerr << "Error opening file test.dat\n";

    std::vector<int> numbers;  // This code is written for one vector only. There would be three vectors for the example file I provided above; one for the vectorOne data in the file, and so on.

    while (true)
    {
        // get first '
        std::getline(theStream, line, '\'');
        // read until second '
        std::getline(theStream, line, '\'');
        std::istringstream myStream( line );

        std::getline( theStream, block, '\n' );  // Edited, from CashCow
        std::istringstream blockstream( block ); // Edited, from CashCow
        std::getline(blockstream, line, '\'');   // Edited, from CashCow


        int i;
        myStream >> i;
        if (myStream.fail())
            break;
        numbers.push_back(i);
    }
    std::copy(numbers.begin(), numbers.end(),
              std::ostream_iterator<int>(std::cout, "\n"));
}
4

1 に答える 1

0

ブロックの先頭に到達したら、行末まで読み取り、文字列を解析します。

std::getline( theStream, block, '\n' );
std::istringstream blockStream( block );
std::getline( blockStream, line, '\'' ); // etc
于 2011-02-15T15:38:12.727 に答える