2013-04-10 49 views
0

我試圖從我的向量寫入數據到一個新的文本文件,在這個過程中創建新的文本文件,下面是我的代碼這樣做,但我得到一個錯誤< <只是飛秒之後,錯誤狀態沒有運營商「< <」匹配這些操作數寫一個向量到一個新的文本文件

struct Weather 
{ 
    int a_data; 
    int b_data; 
    double c_data; 
    double d_data; 
    double e_data; 
    double ans_temp; 
}; 


ofstream &operator << (std::ofstream &f, Weather& obj) 
{ 
f<<obj.a_data;///Etc ...code corresponding to dispaly parameters 
return f; 
}; 

int main() 
{ 
    using std::vector; 
    using std::string; 
    using std::getline; 
    using std::cout; 

    vector<Weather> data_weather; 
    string line; 
    ifstream myfile ("weatherdata.txt"); 

    if (myfile.is_open()) 
    { 
    int count = 0; 
    while (getline(myfile, line)) 
    { 
     if (count > 6) 
     { 
      int a, b; 
      double c, d, e; 
      std::istringstream buffer(line); 
      std::string e_as_string; 
      if (buffer >> a >> b >> c >> d >> e_as_string) 
      { 
       if (e_as_string == "---") 
       { 
        sun = 0.0; 
       } 
       else 
       { 
        std::istringstream buffer2(e_as_string); 
        if (!(buffer2 >> sun)) 
        { 
         sun = 0.0; 
        } 
       } 
       Weather objName = {a, b, c, d, e}; 
       data_weather.push_back(objName); 
      } 
     } 
     count++; 
    } 
    myfile.close(); 

    for (auto it = data_weather.begin(); it != data_weather.end(); ++it) 
    { 
     it->ans_temp = it->c_data + it->d_data /2; 
    } 
    for (auto it = data_weather.begin(); it != data_weather.end(); ++it) 
    { 

     std::cout << it->ans_temp << std::endl; 
    } 

    std::ofstream fs("newdata.txt"); 
      for(vector<Weather>::const_iterator it = data_weather.begin(); it != data_weather.end(); ++it) { 
      fs << *it << '\n'; 
     } 
    } 
    else 

    cout << "unable to open file"; 

    scat::pause("\nPress <ENTER> to end the program."); 

    return 0; 
} 
+3

你是否提供了一個'運營商<<'重載'Weather'? – 2013-04-10 10:38:58

+0

分享天氣課的氣氛。你有重載<<運算符? – shivakumar 2013-04-10 10:40:19

+0

@shivakumar ive更新了問題 – jaylad 2013-04-10 10:49:14

回答

0

好像你還沒有重載< <運營商。

friend ostream &operator << (std::ostream &f, Weather& obj) 
    { 
    f<<obj.a_data; //Etc ...code corresponding to dispaly parameters 
    return f; 
    } 
+0

確定即時通訊新的這個,所以上面的代碼將這個前面放置.... std :: ofstream fs(「newdata.txt」); (vector :: const_iterator it = data_weather.begin(); it!= data_weather.end(); ++ it){0} {* it <<'\ n'; – jaylad 2013-04-10 10:54:12

+0

@jaylad這是一個函數定義。所以它不能用於其他功能。你可以在課後把它放在主要位置之前。你應該谷歌的C + +運算符重載。 – 2013-04-10 10:56:21

+0

謝謝,我會盡...包括此功能定義在主要之前的正確位置,但我仍然得到我以前的原始錯誤? – jaylad 2013-04-10 11:02:52

0
ofstream& operator<< (std::ofstream &f, const Weather& obj) 
             ^^^^ 
{ 
    f<<obj.a_data;///Etc ...code corresponding to dispaly parameters 
    return f; 
}; 

或(不推薦)

for(vector<Weather>::iterator it = data_weather.begin(); it != data_weather.end(); ++it) 
        ^^^^ 
{ 
    fs << *it << '\n'; 
} 
相關問題