Reputation: 333
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
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
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
Reputation: 3995
#include <fstream>
int main()
{
ifstream inputFile (fileInput.c_str());
}
Upvotes: 2
Reputation: 38163
Yes, use .c_str()
method:
ifstream inputFile (fileInput.c_str());
Upvotes: 1