2014-11-04 50 views
0

當我編譯這段代碼時,我總是收到「沒有匹配的函數」錯誤。有人可以幫我解決這個問題嗎?C++中的輸出文件問題

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

編輯:閱讀和displaing文件時 關於什麼的?我遇到了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"); 

} 
+0

它是一個參數(單個字符串參數)函數 - OutFile.open(文件名)。您正在使用一組文件名。你的錯誤堆棧跟蹤應該會顯示給你。改爲使用單個字符串。 – ha9u63ar 2014-11-04 20:26:16

+0

然後請在下一次出現錯誤時告訴我們錯誤發生在哪一行以及您正在使用哪種編譯器。 – 2014-11-04 20:37:37

回答

4

open()採用單個string,而不是字符串的數組。

您正在創建一個數組(一個)。試試這個:

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

我剛剛進行了修正,但仍然給我相同的錯誤 – jon 2014-11-04 20:28:55

+1

您需要使用'filename.c_str()'。如果你刪除了'open',它就不會被改爲使用'std :: string'直到C++ 11 – AndyG 2014-11-04 20:30:08

+0

@jon它不應該[編譯](http://coliru.stacked-crooked.com/a/5376d442732033b4) '[]' – Borgleader 2014-11-04 20:30:50

0

您已經使用string[]代替stringchar[],所以要定義一個字符串數組,而不是單一的字符串。

open接受單個string而不是多個字符串,其中單個string是多個字符/字符數組。