How to insert a variable in a « ifstream » line

Hi ; It seems incredible ifstream does not accept a variable (name of the file) that i get with a cin. May someone help me. Many thanks Here is the code :
/*ver.cpp*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
cout << "Give me please the name of the file\n";
string a_file;
cin >> a_file;
cout << a_file << endl;
ifstream ifs ( a_file );//This line not accepted by the compiler
//ifstream ifs ("verif");//this line works well , for the file named verif
if ( ! ifs ) cout << "fichier inexistant\n";
else cout << "Ce fichier existe\n";
}

What compiler and compiler version are you using?

Are you compiling the program as a C++11 (or higher) program"

Using a std::string with a stream constructor wasn't added until the C++11 standard.

Compiler g++. I don't know how to find its version. Sorry
Wonderfull ! Problem solved. Please tell me where I can find such a complicated solution ? Many thanks.
Compiler g++. I don't know how to find its version. Sorry

g++ --version should give you the compiler version number.


You should be using the -std=c++11 flag (at minimum) when compiling the program to insure you're using at least the C++11 C++ standard. Depending on the version of your compiler you might be able to use the current standard (-std=c++14).

Please tell me where I can find such a complicated solution ?

From looking at the documentation for std::ifstream, you should see that, prior to C++11, there is no constructor that takes a std::string, but that there is one that takes a const char*.

From looking at the documentation for std::string, you should see that you can obtain the contents of the string as a const char* using the c_str() method.
Last edited on
Thanks to all of you. You gave me a lot of information.
Topic archived. No new replies allowed.