Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C+中写入用户指定的文件+; < >我可以指定我想在C++中写入什么文件吗?我希望能够键入文件名并写入该文件。当我试着打开myfile.open(“example.txt”)myfile.open(var)时,我遇到了一个大错误_C++_File Io_Compiler Errors - Fatal编程技术网

在C+中写入用户指定的文件+; < >我可以指定我想在C++中写入什么文件吗?我希望能够键入文件名并写入该文件。当我试着打开myfile.open(“example.txt”)myfile.open(var)时,我遇到了一个大错误

在C+中写入用户指定的文件+; < >我可以指定我想在C++中写入什么文件吗?我希望能够键入文件名并写入该文件。当我试着打开myfile.open(“example.txt”)myfile.open(var)时,我遇到了一个大错误,c++,file-io,compiler-errors,C++,File Io,Compiler Errors,错误:调用“std::basic_of stream>::open(std::string&)”时没有匹配的函数 /usr/include/c++/4.2.1/fstream:650:注:候选项为:void std::basic_of stream::open(const char*,std:_Ios_Openmode)[带_CharT=char,_Traits=std::char_Traits] 你能理解这一点或解释我做错了什么吗?我觉得这很简单,因为这是我第一次使用C++。 < P>如果 v

错误:调用“std::basic_of stream>::open(std::string&)”时没有匹配的函数 /usr/include/c++/4.2.1/fstream:650:注:候选项为:void std::basic_of stream::open(const char*,std:_Ios_Openmode)[带_CharT=char,_Traits=std::char_Traits]

你能理解这一点或解释我做错了什么吗?我觉得这很简单,因为这是我第一次使用C++。

< P>如果<代码> var >代码>,请尝试:


错误会准确地告诉您出了什么问题,尽管名为的模板类型的精度无法帮助您清楚地了解这一点。请看一下参考资料。文件名采用
const char*
,另一个可选模式参数。您传递的不是
const char*

而是
var
a
std::string
?如果是这样,您应该传递
var.c_str()
,因为没有
的变体。open()
接受
std::string
,是变量a
string
char[]
,还是
char*
?我认为open()方法需要一个c样式的字符串,它将是
char[]
char*
,因此在传入字符串时需要调用
.c_str()
方法:

myfile.open(var.c_str());

open调用还有第二个参数。它应该类似于myfile.open(“example.txt”,fstream::out)

正如错误所说,它试图用字符指针匹配参数,而std::string不是字符指针。但是std::string::c_str()将返回一个

尝试:


错误信息非常清楚。它说:
basic_of stream
类(您的文件对象)没有一个名为“open”的成员函数,它只接受一个
string
(您的
var
)类型的参数。您需要从
string
转到
const char*
——为此,您可以使用
var.c_str()

简言之,是的,您可以指定一个文件以多种不同的方式打开和写入。 如果您使用的是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;
}
#包括
#包括
int main()
{
std::string filename=“myfile.txt”;
std::fstream输出文件;
open(filename.c_str(),std::ios::out);

outfile一般来说,您希望发布问题的最小工作示例,否则人们会猜测细节。帮助人们帮助您。@luke我做了,那是
myfile.open(“example.txt”)
。这并没有告诉我们
myfile
被声明为什么,也不是产生错误的那一行。请这样想:您想向我们展示您的程序的最短版本,以演示您遇到的确切问题。我得到一个
错误:“struct std::string”没有名为“c_string”的成员。
您想要的。c_str(),而不是.c_string()。感谢您纠正我的错误。我必须将str自动读取为字符串。:D
myfile.open(var.c_str());
#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;
}