2017-02-22 49 views
-2

我很新的C++,我試圖從一個文本閱讀的2D平面創建點的矢量。爲此,我首先創建一個由兩個值(x,y)組成的稱爲point的結構。然後這些點的矢量稱爲vec。但是我不確定如何在文本文件中三列填充的結構數據!第一列是隻爲點的索引,第二列是x數據和第三是y數據。我不知道的VEC的大小,所以我嘗試使用push_back()這是我到目前爲止所。如何填充從文本文件中矢量有兩列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 

編輯

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; 
}; 

然後有一個向量structur ES:

std::vector<point> points; 

在循環中,創建一個point例如,初始化其xy部件,然後將其推回的points載體。

請注意,上述代碼幾乎沒有任何一種錯誤檢查或容錯。如果文件中存在錯誤,更具體地說,如果格式有問題(例如在一行中有一個額外的數字,或者數字很少),那麼上面的代碼將無法處理它。爲此,您可以使用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. 重複下一行,直到文件的末尾