如何解决"std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)"

How to solve "std::basic_ofstream<char, std::char_traits<char> >::open(std::string&)"

我在编译这段代码时收到关于 std::basic_ofstream<char, std::char_traits<char> >::open(std::string&) 的错误:

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

const char* File = Uname + FileEX;

string File = Uname + FileEXt;

ofstream outFile;
outFile.open(File);

完整代码:

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;
}

这段代码应该创建一个文件,在 DB 目录中存储一个名称。

您正在将 std::string 传递给 ofstream::open()。在 C++11 之前,open() 不接受一个 std::string 作为输入,只接受一个 const char* 指针,例如:

outFile.open(File.c_str());