如何要求用户输入文件并让 c++ 打开此文件

How do i ask a user to enter a file and let c++ open this file?

本文关键字:文件 c++ 用户 输入      更新时间:2023-10-16

简单的 c++ 中是否可以要求用户输入路径并操作相同的文件?有没有人知道一个网站来了解更多关于这个的信息?谷歌这次没那么容易。

#include <iostream>
#include <fstream>
int main()
{
    using namespace std;

    char * b = 0;
    cin >> b;
    cout << b;
    const char * c = b;
    ofstream myfile;
    myfile.open (c);
    myfile << "Writing this to a file.n";
    myfile.close();
    return 0;
}

而不是char*使用std::string

#include <string>
std::string b;

正如代码一样,正在尝试通过 NULL 指针进行写入。

如果不是 C++11,则需要使用 b.c_str() 传递给 myfile.open()

myfile.open(b.c_str()); // Or ofstream myfile(b.c_str());
if (my_file.is_open())
{
    myfile << "Writing this to a file.n";
    myfile.close();
}