0

重複の可能性:
C ++:Xcode(Mac)の問題の可能性。getline()を使用して外部ファイルから数値を読み取ることができません

私はMacXcode(3.2.2)ユーザーであり、GCC 4.2コンパイラーを使用しており、C ++の経験がかなりなく、コンパイラーについて完全に無知です。

外部ファイルから数値を読み取り、それらをintのベクトルに格納する必要があります。ストリームとgetline()を使用してコードを記述しました。コードをコンパイルでき、エラーなしで実行されますが、出力がありません。ただし、友人(MacおよびGCC 4.2以外のコンパイラ)では機能します。

私はいくつかのグーグルを行い、私の問題に関連する可能性のあるXcode 3.2.1のコンパイラ(gcc、Apple)の問題に関するいくつかの投稿を見つけました(これは、たとえば、getline()を使用したC ++プリント:解放されるポインタが割り当てられていませんでしたXCode。ただし、Xcode 3.2.2を使用しています。提案された修正((1)ターゲット設定ウィンドウまたは(2)インクルードの前のプリプロセッサマクロとしての_GLIBCXX_FULLY_DYNAMIC_STRINGの追加に関連する)を試しましたが、問題はまだ解決されていません。

したがって、現時点で私の問題が何であるかはわかりません。Xcode3.2.1で発生したのと同じコンパイラの問題であるかどうかはわかりませんが、3.2.2では別の修正が必要です。または、コードに他の問題がある場合。

誰かがアドバイスをしてくれるといいですね。アドバイスは単純すぎません。外部ファイルから数値をインポートする別の方法がある場合は、それについて知りたいと思います。また、Macの.txtファイルではなく、.datファイルからデータをインポートできる理由があるかどうかを誰かが知っていますか?

ありがとうございました。

最初の投稿以来、私はwilhelmtellの編集を含めました。

目標:テキストファイルから「結果」と呼ばれるintのベクトルに数値を読み取ります。

1)データファイルtest.datのデータは、最初は次のようになりました。

//テスト

テスト

'1''2''3'

//テキストファイルには、読みたくないがファイルから削除できないラベルとコメントもあります。

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

using namespace std;

// Edited: added struct (wilhelmtell's advice)
struct not_digit_and_not_whitespace {
    bool operator()(char c) const {
        return ! std::isdigit(c) && ! std::isspace(c);
    }
};

int main()
{
    system("pwd");

    std::string line;
    const std::string fileName = "/Users/me/test.dat";  

    ifstream theStream( fileName.c_str() ); 

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

    std::getline( theStream, line );
    // line.erase(remove( line.begin(), line.end(), '\'' ), line.end() ); // Edited (wilhelmtell's advice)
    line.erase(remove_if( line.begin(), line.end(),not_digit_and_not_whitespace()), line.end() );  // Edited: added (wilhelmtell's advice)

    std::istringstream myStream( line );
    std::vector<int> numbers((std::istream_iterator<int>(myStream)), std::istream_iterator<int>());

    std::copy(numbers.begin(), numbers.end(),
              std::ostream_iterator<int>(std::cout, "\n"));

    /* int temp;  // Edited: wilhemtell suggested using iterators instead.
    while ( myStream >> temp ){
        numbers.push_back( temp );
     std::cout << temp << std::endl;
    }*/
    return 0;
}
4

0 に答える 0