2012-06-04 101 views
0

你好,我有一個3 int間隔2個空格的列表,我想讀取它們並創建一個對象。我將從數據結構,類和前/後數據粘貼我的代碼。我無法找到錯誤的原因。歡迎任何幫助:從.in文件中讀取對象

Class.h:

class RAngle{ 
private: 
    int x,y,l,b; 
    int solution,prec; 
    RAngle(){ 
     x = y = solution = prec = b = l = 0; 
    } 

    RAngle(int i,int j,int k){ 
     x = i; 
     y = j; 
     l = k; 
     solution = 0; prec=0; b=0; 
    } 

    friend ostream& operator << (ostream& out, const RAngle& ra){ 
     out << ra.x << " " << ra.y<<" " << ra.l <<endl; 
     return out; 
    } 

    friend istream& operator >>(istream& is, RAngle& ra){ 
     is >> ra.x; 
     is >> ra.y; 
     is >> ra.l; 

     return is ; 
    } 

}; 

dataStructure.h:

template <class T> 
class List 
{ 
private: 
    struct Elem 
    { 
     T data; 
     Elem* next; 
    }; 

    Elem* first; 

    void push_back(T data){ 
    Elem *n = new Elem; 
    n->data = data; 
    n->next = NULL; 
    if (first == NULL) 
    { 
     first = n; 
     return ; 
    } 
    Elem *current; 
    for(current=first;current->next != NULL;current=current->next); 
    current->next = n; 
} 

main.cpp中:

void readData(List <RAngle> &l){ 
    *RAngle r; 
    int N; 
    ifstream f_in; 
    ofstream f_out; 

    f_in.open("ex.in",ios::in); 
    f_out.open("ex.out",ios::out); 

    f_in >> N; 
    for(int i=0;i<13;++i){ 
     f_in >> r; 
     cout << r; 
     l.push_back(r); 
    } 

    f_in.close(); 
    f_out.close(); 
}* 

輸入數據:

3 1 2 
1 1 3 
3 1 1 

輸出(在印刷讀取時):

1 2 1 
1 3 3 
1 1 3 

正如你可以看到不知它開始與2速位置讀取並與第一結束。

+0

這是你的代碼的全部?你的課程似乎很奇怪,通常包含'class Foo'的文件被稱爲'Foo.h'或'Foo.cpp'等等。儘管你給了我們一個名爲'main.cpp'的文件,你沒有main()函數。 – jedwards

回答

1

正如你所看到的,它開始讀取第二個位置並以第一個位置結束。

這是因爲您提取了第一個值。

readData功能:

f_in >> N; // This line will extract the first value from the stream. 

// the loop starts at the second value 
for(int i=0;i<13;++i){ 
f_in >> r; 
    cout << r; 
    l.push_back(r); 
} 
+0

謝謝。我想那個fn >> N會計算我的界限,好像我錯了:< –

1

讀取f_in >> N的行首先將計數讀入變量,但輸入文件缺少該計數。 (或者說,它將第一個'3'看作計數,這意味着元組實際上以'1 2 1 ...'開頭)。