1

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?

4 Answers 4

4

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());
Sign up to request clarification or add additional context in comments.

Comments

2
#include <fstream>

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

c_str() is what you want.

Comments

1

Yes, use .c_str() method:

ifstream inputFile (fileInput.c_str());

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.