C++: std::ifstream ifs(路径), 'path should be a constant'
C++: std::ifstream ifs(path), 'path should be a constant'
我想要这样的东西工作:
#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;
}
它应该询问路径,然后写出文件中的所有内容。但它说路径应该是一个常数。我该如何解决?也许我应该改变访问文件的方式?谢谢
你有两个选择(我知道):
- 使用c++11(添加std=c++11编译标志)
- 将
std::ifstream ifs(path)
更改为 std::ifstream ifs(path.c_str())
。这是因为 std::ifstream
constructor takes as input const char*
and you can get this from your string using the c_str()
method 来自 std::string
class.
我想要这样的东西工作:
#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;
}
它应该询问路径,然后写出文件中的所有内容。但它说路径应该是一个常数。我该如何解决?也许我应该改变访问文件的方式?谢谢
你有两个选择(我知道):
- 使用c++11(添加std=c++11编译标志)
- 将
std::ifstream ifs(path)
更改为std::ifstream ifs(path.c_str())
。这是因为std::ifstream
constructor takes as inputconst char*
and you can get this from your string using thec_str()
method 来自std::string
class.