【问题标题】:C++ - Simple ifstream errorC++ - 简单的 ifstream 错误
【发布时间】:2012-11-05 19:43:43
【问题描述】:

谁能帮我弄清楚是谁用 ifstream myfile(fileName); 在用 g++ 编译时产生错误?

string fileName;

cout << "\nPlease enter the name of your input file:" << endl;
cout << "->";
getline (cin, fileName);

cout << "fileName: " << fileName << endl;

string line;
ifstream myfile(fileName);
if (myfile.is_open()){
    while(getline(myfile, line)){
        cout << line << endl;
    }
myfile.close();
} else {
    cout << "Unable to open file"; 
}

【问题讨论】:

    标签: c++ ifstream


    【解决方案1】:

    除非您有 C++11 支持,否则您需要将 const char* 传递给构造函数。你可以这样实现:

    std::ifstream myfile(fileName.c_str());
    

    看到这个documentation for the relevant constructors

    【讨论】:

      【解决方案2】:

      您需要先将其转换为 c 字符串。

      试试 myfile((filename).c_str())

      【讨论】:

      • 不需要额外的括号。
      猜你喜欢
      • 2012-11-06
      • 1970-01-01
      • 2013-11-13
      • 2014-08-16
      • 2013-11-01
      • 2012-04-18
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      相关资源
      最近更新 更多