Search code examples
c++structwritetofile

Structure array writing to text file


I am having problems with file writing function for my structure array. I am getting errors, that could not convert 'cars[n]' from 'car' to 'std::string {aka std::basic_string<char>}'

I am little bit confused with file writing, maybe someone could explain or give me some hints how to make my writing function work?

My code:

#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <fstream>

using namespace std;

#define N_CARS 2

struct car{
    string model;
    int year;
    double price;
    bool available;
    }cars [N_CARS];


void writeToFile(ofstream &outputFile, string x )
{
    outputFile << x << endl;
}


    int main ()
{
  string mystr;
  string mystr2;
  string mystr3;
   int n;

  for (n=0; n<N_CARS; n++)
  {
  cout << "Enter title: ";
  getline (cin,cars[n].model);
  cout << "Enter year: ";
  getline (cin,mystr);
  stringstream(mystr) >> cars[n].year;
  cout << "Enter price: ";
  getline (cin,mystr2);
  stringstream(mystr2) >> cars[n].price;
  cout << "Choose availability: ";
  getline (cin,mystr3);
  stringstream(mystr3) >> cars[n].available;
}
   ofstream outputFile;
    outputFile.open("bla.txt");
    for (n=0; n<N_CARS; n++)
    writeToFile(outputFile, cars[n]);
    outputFile.close();

   system("PAUSE");
  return 0;
}

Am I getting it right that outputFile << x << endl; will write to file my whole struct fields?


Solution

  • Am I getting it right that outputFile << x << endl; will write to file my whole struct fields?

    The following:

    void writeToFile(ofstream &outputFile, string x )
    {
        outputFile << x << endl;
    }
    

    has absolutely nothing to do with your struct or your fields. It writes a string.

    The following:

    writeToFile(outputFile, cars[n]);
    

    invokes a function which accepts an std::string, and tries to pass a car to it. That's not going to work.

    You have a number of options:

    • Output every single member of your structure by yourself, using <<.

    • Overload the << operator for your structure, so that you can actually do outputFile << mycar, where << will be invoking your overloaded operator. (This is the best option.)

    • Make your structure convertible to std::string. This is going to turn around and bite you later, because at some point you will inevitably need to read your structure from a stream, and then you are going to have to make your structure also convertible from string, which means string parsing, which is ugly and error-prone business.