C++中的ifstream不接受变量

MKI*_*KII 0 c++ string fstream getline

我试图使用以下代码片段:

int main()
{
string location_file ("test.txt");
string data;

ifstream file (location_file);
getline (file, data);
file.close();

cout << data;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

但它不会起作用.现在,如果我使用"ifstream文件("test.txt")"它会.为什么?到底是不是一回事?

Oli*_*rth 5

因为在早期版本的C++标准,有(不快)没有构造函数ifstream是花了string,所以你必须要做到:

ifstream file(location_file.c_str());
Run Code Online (Sandbox Code Playgroud)