Matthew Muller
Matthew Muller

Reputation: 333

Am I able to to use a string variable for a file name with fstream? C++

I want to be able to take text input and store it in a string variable like so:

#include <fstream>

int main()
{
    string fileInput = "filetoinput.txt";
    ifstream inputFile (fileInput);
}

But it will only accept creating an ifstream type variable like so:

#include <fstream>

int main()
{
    ifstream inputFile ("filetoinput.txt");
}

Is there a way to make a string variable act like text in quotes?

Upvotes: 1

Views: 317

Answers (4)

Areg Melik-Adamyan
Areg Melik-Adamyan

Reputation: 1

ifstream is using explicit constructor

explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in)

So you need to use strings' const char* c_str() const function to pass parameter.

Upvotes: 0

Pete Becker
Pete Becker

Reputation: 76285

With C++11 the original example should work:

#include <fstream>
#include <string>

std::string fileInput = "filetoinput.txt";
std::ifstream inputFile(fileInput);

If you're not up to C++11, then fileInput.c_str() gives you a C-style string that you can use for the call:

std::ifstream inputFile(fileInput.c_str());

Upvotes: 4

Blacktempel
Blacktempel

Reputation: 3995

#include <fstream>

int main()
{
    ifstream inputFile (fileInput.c_str());
}

c_str() is what you want.

Upvotes: 2

Kiril Kirov
Kiril Kirov

Reputation: 38163

Yes, use .c_str() method:

ifstream inputFile (fileInput.c_str());

Upvotes: 1

Related Questions