简体   繁体   中英

How to solve "std::basic_ofstream<char, std::char_traits<char> >::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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM