C ++:std :: ifstream ifs(path),' path应该是一个常量'

时间:2017-12-03 19:47:39

标签: c++ fstream

我想要这样的事情发挥作用:

#include <iostream>
#include <fstream>
#include <string>
std::string path;
char c;
while (true) {
    cin >> path;
    std::ifstream ifs(path);
    c = ifs.get();
    while (ifs.good()) {
        cout << c << endl;
        c = ifs.get();
    }
    cout << endl;
}

它应该询问路径,然后写出文件中的所有内容。但它说道路应该是一个常数。我该如何解决?也许我应该改变我到达文件的方式?感谢。

1 个答案:

答案 0 :(得分:3)

你有两个选择(我知道):

  1. 使用c ++ 11(添加std = c ++ 11编译标志)
  2. 使用std::ifstream ifs(path)更改std::ifstream ifs(path.c_str())。这是因为std::ifstream constructor将输入const char*作为输入,您可以使用std::string类中的c_str() method从字符串中获取此内容。