将文件保存到C++中用户输入定义的位置和名称

llk*_*llk 0 c++ string text user-input file

我在将在控制台窗口中创建的文本文件保存到由用户输入定义的自定义位置时遇到一些问题.我希望它采用字符串filepath作为保存位置,并将其与字符串组合,该字符串filename将是用户选择的文本文件的名称.比如这个C:\users\bobbert\desktop\c++.txt我想要一个第三个字符串,它将是写入c ++ .txt文件的实际文本.这是我的代码:

cout<<"Please enter a name for your file: "<<endl;
cin>>filename;

cout<<"Please enter a directory to save your file in: "<<endl;
cin>>filepath;

//user is now typing data into the text file
cin>>data;
//the data is now being grabbed and put into the "Data" string

FILE * pFile;
pFile = fopen (filepath.c_str() + filename.c_str(),"a");

//trying to combine the users selected directory + the selected filename here

if (pFile!=NULL)
{
    fputs(data.c_str(), pFile);
    //here i am trying to take the data of the .txt file
    //string and put it into the new file
}

fclose (pFile);
Run Code Online (Sandbox Code Playgroud)

感谢您抽时间阅读!:)

Lig*_*ica 5

filepath.c_str() + filename.c_str()不会连接字符串,因为它们是指向字符数组的指针,而不是C++ std::string对象.你只是[尝试]对指针进行算术运算.

尝试:

std::string filename, filepath, data;

cout << "Please enter a name for your file: " << endl;
cin >> filename;

cout << "Please enter a directory to save your file in: " << endl;
cin >> filepath;

//user is now typing data into the text file
cin >> data;

//the data is now being grabbed and put into the "Data" string
ofstream fs((filepath + "/" + filename).c_str(), ios_base::app);

//trying to combine the users selected directory + the selected filename here
if (fs)
   fs << data;
Run Code Online (Sandbox Code Playgroud)

我已经更换了你的C风格的使用fopen与C++流对象,固定你的字符串问题,并添加之间反斜杠filepathfilename(在安全的情况下,用户不会写).

请注意,您仍然需要执行.c_str()std::string拼接的结果传递完成路径时ofstream的构造,因为输入输出流中的串库之前设计的.这只是一个讨厌的C++ - 主义.