0
votes

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++.

7
In general you want to post the smallest working example of your problem, otherwise people are left guessing at the details. Help people help you. - luke
@luke I did, that was the myfile.open("example.txt"). - CoffeeRain
that doesn't tell us what myfile is declared as, nor is it the line that produces the error. Think of it this way: you want to show us the shortest version of your program that demonstrates the exact problem you're having. - luke

7 Answers

4
votes

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 *.

2
votes

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());
2
votes

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;
}
0
votes

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.

0
votes

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());
0
votes

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

0
votes

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().