2013-10-25 62 views
0

我在這裏發現編碼問題。我需要從文本文件讀取,然後寫入一個對象。但是,我不可能這樣做。對象中的值看起來像沒有被初始化。無法將數據從txt文件寫入對象

void readPolynomial(string filename, polynomial& p) 
{ 
    //Read in the terms of the polynomial from the data file. 
    //Terms in the data file are arranged in descending order by the exponent. 
    //One term per line (coefficient followed by exponent), and there is no blank line. 
    term temp = term(); 
    double c = 0; 
    int e = 0; 
    ifstream fin; 
    fin.open(filename); 

    while(!fin.eof()) 
    { 
    fin >> c >> e; 
    temp = term(c, e); 
    p.addTerm(temp); 
    } 
    fin.close(); 
} 

這裏是類名的頭文件。

默認構造方法:

term() 
{ 
    coef = 0; 
    exp = 0; 
} 

term::term(double c, int e) 
{ 
    c = coef; 
    e = exp; 
} 
+0

什麼(地方)是錯誤您收到? – benjymous

回答

3

看起來你交換的參數和兩個參數的構造函數的成員變量。嘗試:

term::term(double c, int e) 
{ 
    coef = c; 
    exp = e; 
} 
+0

非常感謝。該部分現在運行良好。 :) –

0

此外,你可以重寫你的函數爲:

void readPolynomial(string filename, polynomial& p) 
{ 
    double c = 0; 
    int e = 0; 
    ifstream fin(filename); 

    fin.exceptions(std::ios_base::goodbit); 

    while (fin >> c >> e) 
    { 
     term temp(c, e); 
     p.addTerm(temp); 
    } 

    // Exception handling (optional) 
    try { fin.exceptions(std::ios_base::failbit | 
         std::ios_base::badbit | 
          std::ios_base::eofbit ); 
    } catch(...) 
    { 
     if (fin.bad()) // loss of integrity of the stream 
      throw; 
     if (fin.fail()) // failed to read input 
     { 
      fin.clear(); 
      fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
     } 
     fin.clear(); 
    } 
}