c ++中的输出文件问题

时间:2014-11-04 20:22:22

标签: c++ file

编译此代码时,我一直收到“无匹配函数”错误。有人可以帮我解决这个问题吗?

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>

using namespace std;
int main()
{
  string filename[]="Hello.txt";
  ofstream OutFile;
  OutFile.open(filename);
  if(OutFile.fail()) // check for successfully open ,
   {
    cout << "file named can not be found \n";
    exit(1);
   } 
    OutFile << "Hello, this is my output file";
    OutFile.close();
    system("pause");
    return 0;
}

编辑: 阅读和替换文件时怎么样?我遇到了getline问题而且无法编译。有人能指出那里的问题吗?

#include <iostream>

#include <fstream>

#include <stdlib.h>

#include <string>
using namespace std;

int main()

{

  char filename[] = "Hello.txt";

  string line = "Hello, this is my output file";

  ofstream OutFile;

  OutFile.open(filename);

  if(OutFile.fail()) // check for successfully open ,

   {

     cout << "file named can not be found \n";

     exit(1);

   } 

     OutFile << line;

     if (OutFile.is_open())

       OutFile.getline(line);

    OutFile.close();

     system("pause");

}

2 个答案:

答案 0 :(得分:4)

open()只需一个string,而不是一个字符串数组。

你正在创建一个数组(一个)。试试这个:

string filename = "Hello.txt";
ofstream OutFile;
OutFile.open(filename.c_str());

答案 1 :(得分:0)

您使用string[]代替stringchar[],因此您定义的是字符串数组,而不是单个字符串。

open接受单个string而不是多个字符串,其中单个string是多个字符/字符数组。