根据用户输入的字符串命名输出文件

Naming an output file from a user entered string

本文关键字:输出 文件 字符串 用户 输入      更新时间:2023-10-16

这是我在C++的第一个项目。我以前参加了一门使用 C 的课程,文件 I/O 似乎略有不同。

该项目要求用户输入用于保存输出文件的名称。

我知道我应该使用 ofstream,它应该看起来像这样:

ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.n";
myfile.close();

我已经将引起混乱的片段加粗了。
如何从用户输入的字符串中命名文件?
*注意,C类型字符串,所以是一个字符数组。
不允许 #include <字符串>

由于我的另一个答案得到了反对票,这是另一种解决方案,没有#include <string>

您可以将用户的输入保存在临时 char 数组中,然后将其保存到字符串变量 std::string 中。

包括必要的:

#include <iostream>
#include <fstream>

将用户的输入保存到 char 数组中:

char input[260];
cin >> input;

然后将其保存在字符串变量中,只需执行以下操作:

string filename = input;

要打开文件流,您需要使用 std::ofstream .请记住,该文件是在与项目/应用程序相同的文件夹中创建的。

std::ofstream outfile (filename + "." + "file extension");

如您所知,此outfile.open();会打开文件。

使用outfile << "hello";您可以写入文件。

若要关闭文件,请使用outfile.close();关闭文件。

这里有一个小示例代码:

#include <iostream>
#include <fstream>
using namespace std;
void main()
{
    char input[260];
    cin >> input;
    string filename = input;
    ofstream outfile(filename + "." + "txt");
    outfile << "hello";
    outfile.close();
}

我希望这有所帮助。

问候。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string path;
string name;
string h_path;
string text;
void create() {
    ofstream file(h_path, ios::app);
    if (!file.fail()) {
        file << text;
        file.close();
    }
}
int main() {
    cout << "please enter path(c:\folder): ";
    cin >> path;
    cin.ignore();
    path = path + "/";
    cout << "please enter the name of the file (test.txt): ";
getline(cin, name);
    cout << "content of the file: ";
    getline(cin, text);
    h_path = path + name;
    create();
    cout << "new file created";
    cout << h_path;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    string fileName;
    cin >> fileName;
    ofstream myfile;
    myfile.open(fileName);
    myfile << "Writing this to a file.n";
    myfile.close();
}