-1

This has worked fine on some compilers... Is there a way of doing this were it will just work without it being a problem with different compilers on c++11 or c++14?

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void save_file() {
    string file;
    ofstream os;
    cout << "Save As: ";
    getline(cin, file, '\n');
    os.open(file + ".dat");
    //rest of code
}

error: no viable conversion from 'basic_string, std::allocator >' to 'const char *'

So I google it, found some answers, or in this case, canswers (cancers), tried

os.open(file.c_str() + ".dat");

error: invalid operands to binary expression ('const char *' and 'const char *')

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
StackAttack
  • 1,139
  • 1
  • 9
  • 15

3 Answers3

1

Accoding to the C++11 standard 27.9.1.10 one of the constructors for a basic_ofstream is:

explicit basic_ofstream(const string& s, ios_base::openmode mode = ios_base::out);

This means that any standard compliant compiler should be able to compile:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string file = "temp";
    ofstream os;
    os.open(file + ".dat");
}

Live Example

Don't forget that you need to use the -std=c++11 or higher flag when compiling.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

"+" operator cannot be used for the C-style strings. Try this:

string name = file+".dat";
os.open(name.c_str());

You create the std::string type as a concatenation in c++ style and then pass it to open as a c string.

Hitokage
  • 733
  • 8
  • 19
1

In C++11, os.open( file + ".dat" ) works just fine. Pre C++11, there was no std::ofstream::open which took a string, so you had to write os.open( (file + ".dat").c_str() ). Note the parentheses and where the .c_str() goes---you have to concatenate with the std::string first, and only call .c_str() on the results.

James Kanze
  • 150,581
  • 18
  • 184
  • 329