Hi,
The program I'm making to teach myself C++ uses a user-specified file and then does the opening and read/write whatever stuff.

The error i get is this when trying to compile the read_file.open(in_file) line: "no matching function for call to 'std::basic_ifstream,char, std::char_traits> >::open(std::string&)'"

Please help
Thanks

#include <iostream>
#include <string>
using namespace std;
int main()
{
	ifstream read_file;
	ofstream write_file;
	string in_file;
	string out_file;
	getline(cin, in_file, '\n');
	getline(cin, out_file, '\n');
	read_file.open(in_file);
        ***Above line causes the error***

Recommended Answers

All 4 Replies

It's because open() expects a null terminated string rather than a string class. you can do the following

read_file.open(in_file.c_str());

Chris

Nevermind.
Answered my own question.
I suppose some googling first wouldn't have hurt.

For anyone who's still curious about this, use the following extension on any variable you want to use as a filename, .c_str() Like so:

getline(cin, in_file, '\n');
read_file.open(in_file.c_str());

^^ My above posted answered that and explained why.

If thats all mark the thread as solved

Chris

It's because open() expects a null terminated string rather than a string class. you can do the following

read_file.open(in_file.c_str());

Chris

Wow. Very quick answer. Thank you very much. I didn't even have time to post my response to my own question before you answered.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.