CoffeeRain
CoffeeRain

Reputation: 4522

Write to user specified file in C++

Can I specify what file I want to write into in C++? I want to be able to type in the filename and write into that file. When I try making myfile.open("example.txt") myfile.open(var), I get a big error...

error: no matching function for call to ‘std::basic_ofstream >::open(std::string&)’ /usr/include/c++/4.2.1/fstream:650: note: candidates are: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits]

Can you make any sense of this or explain what I am doing wrong? I have a feeling this is very simple, as this is my first week using C++.

Upvotes: 0

Views: 2480

Answers (7)

Kerr
Kerr

Reputation: 431

In short, yes you can specify a file to open and write into many different ways. If you're using an fstream and want to write plain text out, this is one way:

#include <string>
#include <fstream>
int main()
{
  std::string filename = "myfile.txt";
  std::fstream outfile;
  outfile.open( filename.c_str(), std::ios::out );
  outfile << "writing text out.\n";
  outfile.close();
  return 0;
}

Upvotes: 2

luke
luke

Reputation: 37433

If var is an std::string, try:

myfile.open(var.c_str());

The error tells you exactly what's wrong, although the precision of the template types named doesn't help make that crystal clear. Take a look at the reference for .open(). It takes a const char * for the filename, and another optional mode parameter. What you are passing is not a const char *.

Upvotes: 4

Seva Alekseyev
Seva Alekseyev

Reputation: 61331

The error message is quite clear. It says: the basic_ofstream class (your file object) does not have a member function that's called "open" and takes a single argument of type string (your var). You need to go from string to const char * - for that, you use var.c_str().

Upvotes: 0

IronMensan
IronMensan

Reputation: 6821

Like the error says, it is trying to match the parameters with a character pointer and std::string is not a character pointer. However std::string::c_str() will return one.

try:

myfile.open(var.c_str());

Upvotes: 2

v01d
v01d

Reputation: 1507

There is a second parameter to the open call. it should be like myfile.open("example.txt", fstream::out)

Upvotes: 0

Herms
Herms

Reputation: 38788

Is your variable a string, char[], or char*? I think the open() method wants a c-style string, which would be char[] or char*, so you'd need to call the .c_str() method on your string when you pass it in:

myfile.open(var.c_str());

Upvotes: 0

FatalError
FatalError

Reputation: 54541

Is var a std::string? If so, you should be passing var.c_str() as there is not a variant of .open() that takes a std::string.

Upvotes: 0

Related Questions