2012-02-01 45 views
0

我可以指定要在C++中写入什么文件吗?我希望能够输入文件名并写入该文件。当我尝试做myfile.open("example.txt")myfile.open(var),我得到一个很大的错误...用C++写入用户指定的文件

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]

你能把这个任何意义或解释什么,我做错了什么?我有一种感觉,这很简单,因为这是我第一周使用C++。

+0

一般来说,你想发布您的问题的最小工作实例,否则人们在细节左猜测。帮助人们帮助你。 – luke 2012-02-01 19:22:58

+0

@luke我做了,就是'myfile.open(“example.txt”)'。 – CoffeeRain 2012-02-01 19:26:30

+0

,它没有告诉我们'myfile'被声明为什么,也不是产生错误的那一行。您可以这样想:您想向我们展示您的程序的最短版本,以显示您遇到的具体问题。 – luke 2012-02-01 19:33:00

回答

4

如果varstd::string,尝试:

myfile.open(var.c_str()); 

的这个错误告诉你到底出了什么问题,虽然命名模板类型的精度不帮助那晶莹。看看.open()的参考。它需要一个const char *作为文件名,另一个可选的模式参数。你传递的不是const char *

+0

我得到一个错误:'struct std :: string'没有名为'c_string'的成员 – CoffeeRain 2012-02-01 19:25:11

+1

你想.c_str(),而不是.c_string()。 – luke 2012-02-01 19:29:53

+0

感谢您纠正我的错误。我必须自动将str读取为字符串。 :d – CoffeeRain 2012-02-01 19:32:45

0

var a std::string?如果是这样,你应该通过var.c_str(),因为没有.open()的变体,需要std::string

0

是你的变量a stringchar[]char*?我觉得open()方法想要一个C风格的字符串,这将是char[]char*,所以你需要调用.c_str()方法上的字符串时,你把它传递:

myfile.open(var.c_str()); 
0

有一个公开呼叫的第二个参数。它应该像myfile.open(“example.txt”,fstream :: out)

2

就像错误说的那样,它试图将参数与字符指针匹配,并且std :: string不是字符指针。然而std :: string :: c_str()会返回一个。

尝试:

myfile.open(var.c_str()); 
0

错误消息是很清楚。它说:basic_ofstream类(你的文件对象)没有一个叫做“open”的成员函数,并且只有一个类型为string(你的var)的参数。您需要从stringconst char * - 为此,您使用var.c_str()

2

总之,是的,你可以指定一个文件打开并写入许多不同的方式。 如果您使用的是fstream的,并希望写纯文本出来,这是一个办法:

#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; 
}