How to Solve "Std: :Basic_Ofstream: :Open(Std: :String&)"

I get an error about std::basic_ofstream<char, std::char_traits<char> >::open(std::string&) when compiling this code:

FileEXt = ".conf";
const char* FileEX = FileEXt.c_str();

const char* File = Uname + FileEX;

string File = Uname + FileEXt;

ofstream outFile;
outFile.open(File);

Full code:

LPCSTR lpPathName = ".\\DB";

SetCurrentDirectoryA(lpPathName);

string Uname, Pword;
cout << "Please enter a name: ";
cin >> Uname;

cout << '\n' << '\n';
cin >> Pword;
            
system("CLS");
cout << "Username: " << Uname << '\n' << "Password: " << Pword << '\n';

const char* FileEXt = ".conf";
const char* Unames = Uname.c_str();
const char* FileEX = FileEXt;

string File = Uname + FileEXt;

ofstream outFile;
outFile.open(File);

if ( outFile.fail() )
{
    outFile << Uname << '\n' << Pword;
    outFile.close();
}
else
{
    cout << Uname << " already exists!" << '\n';
    Sleep(3000);
    return 0;
}

This code is supposed to create a file that stores a name in the DB directory.

8

1 Answer

You are passing a std::string to ofstream::open(). Prior to C++11, open() did not accept a std::string as input, only a const char* pointer, eg:

outFile.open(File.c_str());
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest