2017-02-22 5 views
-2

私はC++の新機能で、テキストファイルから読み込んだ2次元平面に点のベクトルを作成しようとしています。これを行うには、まず、pointという2つの値(x、y)からなる構造体を作成します。次に、vecと呼ばれるこれらの点のベクトル。しかし、私はどのようにテキストファイルが3つの列にあるときに構造体データを設定するのか分からない!最初の列はポイントのインデックスに、2列目はxデータ、3列目はyデータです。私はvecのサイズを知らないので使用しようとしていますpush_back()これまで私がこれまで持っていたことはここにあります。2つの列を持つテキストファイルからベクトルを取り込む方法C++

int main(){ 

     struct point{ 
std::vector<x> vec_x; 
std::vector<y> vec_y; 
    }; 

    std::vector<point> vec; 
    vec.reserve(1000); 
    push_back(); 

    ifstream file; 
    file.open ("textfile.txt"); 
     if (textfile.is_open()){ 


/* want to populate x with second column and y with third column */ 
     } 
     else std::cout << "Unable to open file"; 
    } 

コメントは次のとおりです。

while(file >> x) 
vec.push_back (x); 


while(file >> y) 
vec.push_back (y); 

これは非常に簡単ですが、私には謝罪です!以下は、6ポイントしかないtxtファイルの例です。

0 131 842 
1 4033 90 
2 886 9013490 
3 988534 8695 
4 2125 10 
5 4084 474 
6 863 25 

EDIT

while (file >> z >> x >> y){ 

    struct point{ 
     int x; 
     int y; 
    }; 

    std::vector<point> vec; 
    vec.push_back (x); 
    vec.push_back (y); 

} 

答えて

4

あなたは、ループ内の通常の入力演算子>>使用することができます:構造用として

int x, y; // The coordinates 
int z;  // The dummy first value 

while (textfile >> z >> x >> y) 
{ 
    // Do something with x and y 
} 

を、私は少しを提案異なるアプローチ:

struct point 
{ 
    int x; 
    int y; 
}; 

次に構造化ベクトルES:ループで

std::vector<point> points; 

、次いでpointsベクターにそれを押し戻す、そのxy部材を初期化する、pointインスタンスを作成します。

上記のコードには、エラーチェックやフォールトトレランスはほとんどありません。ファイルにエラーがある場合、具体的にはフォーマットに問題がある場合(たとえば、1行に余分な数字を1つ、または数字を少しずつ)、上記のコードはそれを処理できません。そのためにはstd::getlineを使用して行全体を読み取ってstd::istringstreamに入れ、文字列ストリームの変数xyを読み込みます。一緒にすべてを置く


、(不正な入力の取り扱いなし)作業コードの簡単な例は、

#include <fstream> 
#include <vector> 

// Defines the point structure 
struct point 
{ 
    int x; 
    int y; 
}; 

int main() 
{ 
    // A collection of points structures 
    std::vector<point> points; 

    // Open the text file for reading 
    std::ifstream file("textfile.txt"); 

    // The x and y coordinates, plus the dummy first number 
    int x, y, dummy; 

    // Read all data from the file... 
    while (file >> dummy >> x >> y) 
    { 
     // ... And create a point using the x and y coordinates, 
     // that we put into the vector 
     points.push_back(point{x, y}); 
    } 

    // TODO: Do something with the points 
} 
+0

ようなものになるだろうあなたの助けをありがとう!私はまだこれに苦しんでいます。私は質問を編集しました。正しい軌道にいるかどうか教えてください。乾杯! – AngusTheMan

+0

@AngusTheManちょっとしたことですが、また多くの。簡単なサンプルプログラムのための私の更新された答えを見てください。 –

+0

ありがとうございました! – AngusTheMan

0
  1. std::getline()

  2. スプリットhere

  3. プッシュ前夜に述べたように空白の文字列を使用してラインを読みますry要素をベクトルに追加します。次の行のための

  4. 繰り返し、ファイルの最後まで

関連する問題