c++ - fstream .open and appending .txt or .dat to filename -


this has worked fine on compilers... there way of doing work without being problem 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 'basic_string, std::allocator >' 'const char *'

so google it, found answers, or in case, canswers (cancers), tried

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

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

accoding c++11 standard 27.9.1.10 1 of constructors basic_ofstream is:

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

this means standard compliant compiler should able 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 need use -std=c++11 or higher flag when compiling.


Comments