char NAME[256];
cin.getline (NAME,256);
ofstream fout("NAME.txt"); //NAME???????
我需要做什麼來創建帶有NAME名稱的文件?如何創建變量名稱的流文件?
char NAME[256];
cin.getline (NAME,256);
ofstream fout("NAME.txt"); //NAME???????
我需要做什麼來創建帶有NAME名稱的文件?如何創建變量名稱的流文件?
你可以嘗試:
#include <string>
#include <iostream>
#include <fstream>
int main() {
// use a dynamic sized buffer, like std::string
std::string filename;
std::getline(std::cin, filename);
// open file,
// and define the openmode to output and truncate file if it exists before
std::ofstream fout(filename.c_str(), std::ios::out | std::ios::trunc);
// try to write
if (fout) fout << "Hello World!\n";
else std::cout << "failed to open file\n";
}
的一些有用參考:
像這樣:
#include <string>
#include <fstream>
std::string filename;
std::getline(std::cin, filename);
std::ofstream fout(filename);
在老版本的C++的最後一行必須是:
std::ofstream fout(filename.c_str());
你可以試試這個。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string fileName;
cout << "Give a name to your file: ";
cin >> fileName;
fileName += ".txt"; // important to create .txt file.
ofstream createFile;
createFile.open(fileName.c_str(), ios::app);
createFile << "This will give you a new file with a name that user input." << endl;
return 0;
}
是你的問題真的如何將char數組傳遞給函數調用? – moooeeeep