字符串变量.open支持预定的字符串变量

Does ofstream variable.open support predetermined string variables?

本文关键字:字符串 变量 支持 open      更新时间:2023-10-16

我的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);

我的水晶球今天有点多云,但我想我能看到一些东西。。。

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

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

假设filename的类型为std::string,则不能将其直接传递给流构造函数:您需要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语句。