-1

这在某些编译器上运行良好......有没有办法做到这一点,它可以正常工作而不会成为 c++11 或 c++14 上的不同编译器的问题?

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void save_file() {
    string file;
    ofstream os;
    cout << "Save As: ";
    getline(cin, file, '\n');
    os.open(file + ".dat");
    //rest of code
}

错误:没有从 'basic_string, std::allocator >' 到 'const char *' 的可行转换

所以我用谷歌搜索,找到了一些答案,或者在这种情况下,canswers(癌症),试过了

os.open(file.c_str() + ".dat");

错误:二进制表达式的操作数无效('const char *' 和 'const char *')

4

3 回答 3

1

“+”运算符不能用于 C 风格的字符串。尝试这个:

string name = file+".dat";
os.open(name.c_str());

您将 std::string 类型创建为 c++ 样式的串联,然后将其作为 ac 字符串传递给打开。

于 2015-07-13T17:01:18.437 回答
1

根据 C++11 标准 27.9.1.10,basic_ofstream 的构造函数之一是:

explicit basic_ofstream(const string& s, ios_base::openmode mode = ios_base::out);

这意味着任何符合标准的编译器都应该能够编译:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string file = "temp";
    ofstream os;
    os.open(file + ".dat");
}

现场示例

不要忘记-std=c++11编译时需要使用或更高的标志。

于 2015-07-13T17:01:04.080 回答
1

在 C++11 中,os.open( file + ".dat" )工作得很好。在 C++11 之前,没有std::ofstream::openwhich 需要一个字符串,所以你必须写os.open( (file + ".dat").c_str() ). 注意括号和去哪里.c_str()---你必须与第一个连接std::string,并且只调用.c_str()结果。

于 2015-07-13T17:58:43.953 回答