2015-04-23 26 views
-2

我試圖將兩列數據x和y放入兩個向量中,一個只包含x,另一個只包含y。沒有列標題。 像這樣:C++:將文件(未知大小的數據)輸入到矢量問題

x1 y1 
x2 y2 
x3 y3 

然而,當我運行此代碼,我遇到了一個錯誤:(LLDB) 誰能告訴我,如果我做錯了什麼?

#include <iostream> 
#include <cmath> 
#include <vector> 
#include <fstream> 

using namespace std; 

int main() { 

    vector <double> x; 
    vector <double> y; 

    ifstream fileIn; 

    fileIn.open("data.txt"); //note this program should work for a file in the above specified format of two columns x and y, of any length. 

    double number; 

    int i=0; 

    while (!fileIn.eof()) 
    { 
     fileIn >> number; 
     if (i%2 == 0) //while i = even 
     { 
      x.push_back(number); 
     } 
     if (i%2 != 0) 
     { 
      y.push_back(number); 
     } 
     i++; 
    } 
    cout << x.size(); 
    cout << y.size(); 

    fileIn.close(); 
    return 0; 
} 
+1

什麼,具體而言,是你看到的錯誤? – dg99

回答

0

的說法如果Data.txt文件無法打開,該程序在一個無限循環進入,如果你殺了它(按Ctrl + C),消息「LLDB」是調試器的名稱。你應該寫這樣的東西:

fileIn.open("data.txt"); //note this program ... 
if(!fileIn) { // check if fileIn was opened 
    cout << "error opening data.txt\n"; 
    return 1; 
} 

並參見。 另外,

while (!fileIn.eof())

是不正確的方式來閱讀您的文件。請參閱: Reading a C file, read an extra line, why?

0

我認爲這不是你的代碼。 檢查你的G ++

g++ -o angle *.cpp -Wall -lm