0

是否可以在简单的 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;
}
4

1 回答 1

1

而不是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();
}
于 2012-05-25T15:51:50.317 回答