6

我真的需要你的帮助。看来我不能在 C++ 中进行文件操作。我使用 fstream 进行了一些文件操作,但是当我编译它时,会出现一个错误,上面写着:

|63|error: no matching function for call to 'std::basic_fstream<char>::open(std::string&, const openmode&)'|

我犯了什么错误?

以下是部分源代码:

#include<stdio.h>
#include<iostream>
#include<fstream>
#include<string>    

using namespace std;

inline int exports()
{
string fdir;
// Export Tiled Map
cout << "File to export (include the directory of the file): ";
cin >> fdir;
fstream fp; // File for the map
fp.open(fdir, ios::app);
if (!fp.is_open())
    cerr << "File not found. Check the file a file manager if it exists.";
else
{
    string creator, map_name, date;
    cout << "Creator's name: ";
    cin >> creator;
    cout << "\nMap name: ";
    cin >> map_name;
    cout << "\nDate map Created: ";
    cin >> date;
    fp << "<tresmarck valid='true' creator='"+ creator +"' map='"+ map_name +"'   date='"+ date +"'></tresmarck>" << endl;
    fp.close();
    cout << "\nCongratulations! You just made your map. Now send it over to tresmarck@gmail.com for proper signing. We will also ask you questions. Thank you.";
}
return 0;
}
4

2 回答 2

6

fstream::open()接受std::string类型作为文件名的 是在 C++11 中添加的。-std=c++11使用标志编译或fdir.c_str()用作参数(改为传递const char*)。

请注意,fstream()如果提供了文件名,构造函数可以打开文件,这将消除对 的调用fp.open()

if (std::cin >> fdir)
{
    std::fstream fp(fdir, std::ios::app); // c++11
    // std::fstream fp(fdir.c_str(), std::ios::app); // c++03 (and c++11).
    if (!fp.is_open())
    {
    }
    else
    {
    }
}
于 2013-04-02T11:00:01.727 回答
4

您需要启用 C++11 模式才能使std::basic_fstream<char>::open(std::string&, const openmode&)重载可用。

将其中之一传递给 gcc:

-std=c++11或者-std=c++0x

在 C++11 之前,istream::open函数只接受 C 字符串。(你可以这样称呼它 fp.open(fdir.c_str(), ios::app);

于 2013-04-02T11:00:06.527 回答