-1

Need help fixing my code, not sure what's wrong. I'm using C++11, trying to write a vector to a file by individually writing each struct. The section of code returning an error is:

string craigSave = "craigSave.txt";
ofstream file(craigSave.c_str());
file.open("craigSave.txt");
for (int i=0; i<finalVector.size(); i++){
    file << finalVector[i]<<endl;
}
file.close("craigSave.txt");
cout<<"Thanks for shopping!"<<endl;
done = true;

The error returned is on the "file.close" line and is:

error: no matching function for call to 'std::basic_ofstream::close(const char [14])'

I research on this error seems to point to needing to use char* as an argument instead of a string, but I'm using C++11, so it should accept strings. Also it is strange that there is no error for the file.open line, as all research shows the error being there, not at file.close

Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
Sam Berger
  • 11
  • 1
  • 2
    `close` doesn't take any parameters. Where are you doing your research? (Wherever it is, go [here](http://en.cppreference.com/w/) instead.) – molbdnilo Sep 14 '16 at 19:40
  • 1
    The constructor opened the file. There's no need for the call to `file.open()`. The destructor will close the file; there's no need for the call to `file.close()`. – Pete Becker Sep 14 '16 at 19:48

1 Answers1

4

Just use file.close();, there's no need to pass the file name again.

See http://www.cplusplus.com/reference/fstream/ofstream/close/.

Also, ofstreams are RAII objects, which means that the file will automatically be closed once the ofstream object goes out of scope (see do I need to close a std::fstream?):

{
    ofstream out("name");
    // do something with out...
} // out.close is called automatically
rainer
  • 6,769
  • 3
  • 23
  • 37
  • 1
    Better yet, remove the line altogether. – AndyG Sep 14 '16 at 19:41
  • True, I'll expand the answer. Thanks! – rainer Sep 14 '16 at 19:42
  • Thanks! Follow-up question, since I haven't specified a location for that file, where does it look for it? In the same folder as the .cpp itself?> – Sam Berger Sep 16 '16 at 15:01
  • @SamBerger In the application's working directory, ie. the directory you started the application from. – rainer Sep 16 '16 at 15:20
  • @SamBerger BTW, if the answer solved your problem, you can [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) it. – rainer Sep 16 '16 at 15:24