将矢量写入新的文本文件

时间:2013-04-10 10:37:30

标签: c++ vector text-files

我试图将数据从我的矢量写入新的文本文件,在此过程中创建新的文本文件,下面是我执行此操作的代码,但我得到的错误是<<就在fs之后,错误状态没有运算符“<<”匹配这些操作数

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

2 个答案:

答案 0 :(得分:0)

好像你没有超载&lt;&lt;操作

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

答案 1 :(得分: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';
}