I have tried to use the following snippet of code:
int main()
{
string location_file ("test.txt");
string data;
ifstream file (location_file);
getline (file, data);
file.close();
cout << data;
return 0;
}
But it won’t work. Now, if I were to use “ifstream file (“test.txt”)” it would. Why? Isn’t it the same thing in the end?
The problem is that
ifstream‘s constructor does not accept astringas parameter, but only achar const*. Now"test.txt"is of typechar const[9]which decays intochar const*according to type promotion rules, therefore it works. However, there’s no implicit conversion fromstringtochar const*, therefore your code doesn’t work.To fix your code, construct your stream with: