如何将字符串传递给文件名的ofstream::open 这是我的第一个C++应用程序。我使用Visual C++ 2010 Express。我正在尝试编写一个控制台程序,每10秒将行“alive”写入我的WD USB硬盘上的alive.txt文件,以防止硬盘旋转。我希望程序提示我输入驱动器号,然后用它告诉程序文件的位置。这项工作: while (true) { Sleep(5000); cout << "Past sleep"; ofstream AliveFile; AliveFile.open ("j:\\alive.txt"); AliveFile << "alive" << endl; AliveFile.close(); } return 0; while(true) { 睡眠(5000); 库特

如何将字符串传递给文件名的ofstream::open 这是我的第一个C++应用程序。我使用Visual C++ 2010 Express。我正在尝试编写一个控制台程序,每10秒将行“alive”写入我的WD USB硬盘上的alive.txt文件,以防止硬盘旋转。我希望程序提示我输入驱动器号,然后用它告诉程序文件的位置。这项工作: while (true) { Sleep(5000); cout << "Past sleep"; ofstream AliveFile; AliveFile.open ("j:\\alive.txt"); AliveFile << "alive" << endl; AliveFile.close(); } return 0; while(true) { 睡眠(5000); 库特,c++,C++,试一试- 你确定DriveLetter是一个只有一个字母的字符串吗?你检查过它的长度吗?你尝试过用调试器调试你的程序吗?啊,这很有意义。我想我需要在它周围加引号。谢谢!通常只有在你构造一个参数字符串用于系统或shell调用时才需要引号。 string DriveLetter; cout << "What is the drive letter for the drive you want to keep awake?" << endl; getline(cin, Driv

试一试-


你确定
DriveLetter
是一个只有一个字母的字符串吗?你检查过它的长度吗?你尝试过用调试器调试你的程序吗?啊,这很有意义。我想我需要在它周围加引号。谢谢!通常只有在你构造一个参数字符串用于系统或shell调用时才需要引号。
string DriveLetter;
cout << "What is the drive letter for the drive you want to keep awake?" << endl;
getline(cin, DriveLetter);
cin.clear();
string Path;
Path = "\"" + DriveLetter + ":\\alive.txt\"";
cout << Path << endl;

while (true)
{
Sleep(10000);
ofstream AliveFile;
AliveFile.open ( Path );
AliveFile << "alive" << endl;
AliveFile.close();
} 
return 0;
Path = "\"" + DriveLetter + ":\\alive.txt\"";  // Why adding \ before the root. 
Path = DriveLetter + ":\\alive.txt\";