ofstream variable.open是否支持预定的字符串变量?

时间:2012-02-10 02:00:46

标签: c++ ofstream

我的IDE在最后一行遇到“filename”变量问题。有人能指出我为什么吗?

    switch(filename_selection)
    {
        case 1: filename_selection = 1;
        filename = "foo3.sql";
        break;

        case 2: filename_selection = 2;
        filename = "foo2.sql";
        break;

        case 3: filename_selection = 3;
        filename = "foo1.sql";
        break;

        default:
        cout << "Invalid selection." << endl;
        break;
    }
    ofstream File;
    File.open(filename, ios::out | ios::trunc);

2 个答案:

答案 0 :(得分:4)

今天我的水晶球有点混乱,但我想我能看到一些......

<psychic-powers>
您的filename被声明为std::string filename;。遗憾的是,在C ++ 03中,std::(i|o)fstream类没有接受std::string个变量的构造函数,只有char const*个。

解决方案:通过filename.c_str() </psychic-powers>

答案 1 :(得分:1)

假设 filename 的类型为 std :: string ,那么你无法直接将它传递给ofstream构造函数:你需要c_str的强大功能()

switch(filename_selection)
{
  case 1:
    //filename_selection = 1; WHAT IS THIS?
    filename = "foo3.sql";
    break;

  case 2:
    ///filename_selection = 2; ???
    filename = "foo2.sql";
    break;

  case 3:
    ///filename_selection = 3; ???
    filename = "foo1.sql";
    break;

  default:
    cout << "Invalid selection." << endl;
    break;
}
ofstream File;
File.open(filename.c_str(), // <<<
          ios::out | ios::trunc);

你似乎也误解了如何使用switch statement