【问题标题】:using string to pass filename to fstream使用字符串将文件名传递给 fstream
【发布时间】:2012-10-26 11:18:53
【问题描述】:

我正在使用下面的方法来读取一个txt文件

modelStream.open("file.txt", ios::in);
if (modelStream.fail())
    exit(1);
model = new Model(modelStream);

但我想知道如何将字符串作为参数传递

string STRING;
modelStream.open(STRING, ios::in);
if (modelStream.fail())
    exit(1);
model = new Model(modelStream);

有谁知道这是否可行,如果可行,我该怎么做?

【问题讨论】:

    标签: c++ string fstream


    【解决方案1】:

    由于遗留原因,C++03 中的 iostreams 需要一个 C 风格、以 null 结尾的字符串作为参数,并且不理解 std::string。幸运的是,std::string 可以使用函数std::string::c_str() 生成 C 风格、以空结尾的字符串:

    modelStream.open(STRING.c_str(), ios::in);
    

    这实际上是在 C++11 中“修复”的,所以如果您使用它,您的原始代码将可以正常工作。

    另外,不建议使用全大写的变量名;也不是一个名为“字符串”的变量。让名字描述含义。

    【讨论】:

      【解决方案2】:

      只需使用std::stringc_str ()方法

      modelStream.open(STRING.c_str (), ios::in);

      【讨论】:

        【解决方案3】:

        标准流不接受标准字符串,只接受 c 字符串!所以使用 c_str() 传递字符串:

        modelStream.open(STRING.c_str(), ios::in);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-19
          • 2018-09-05
          • 1970-01-01
          • 2022-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多