2016-09-26 142 views
2

我寫了一個C++代碼來在循環中創建一些文件名。例如,我將運行循環八次創造8個文本文件,如:嘗試在C++中打開文件時出現錯誤

input0.txt, input1.txt,......., input7.txt 

我的示例代碼如下:

#include<iostream> 
#include<cstdio> 
#include<string.h> 
#include<stdlib.h> 
#include<fstream> 
#include <sstream> 
using namespace std; 

std::string to_string(int i) { 
    std::stringstream s; 
    s << i; 
    return s.str(); 
} 

int main() 
{ 
    FILE *fp; 
    int i=0; 
    string fileName; 
    string name1 = "input"; 
    string name2 = ".txt"; 
    while(i<=7) 
    { 
     fileName = name1+ to_string(i)+ name2; 
     cout<<fileName<<"\n"; 
     fp=fopen(fileName,"r"); 
     i++; 
    } 

} 

但是,當我運行代碼,我得到出現以下錯誤:

error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'FILE* fopen(const char*, const char*)' 

代碼中有什麼問題嗎?解決辦法是什麼?

+3

'fopen(filename.c_str(),「r」)'將解決您的問題。 – muXXmit2X

+0

**使用C++ 11 **,I/O流,您也可以刪除'to_string'實現。 – LogicStuff

+0

另外,您的代碼中沒有'#include '。你依靠編譯器的實現來提供這個頭文件,而不用你指定它,並且不能保證這個頭文件將被包含。 – PaulMcKenzie

回答

5

看看你得到的錯誤信息。

fopen()需要const char*而不是std::string作爲參數。要獲得字符串的const char*,請使用.c_str()函數。

fopen()雖然是c-api。作爲替代,你也可以使用C++的文件流。

std::fstream for read/write and std::ifstream僅供輸入。 std::ofstream僅用於輸出。

1
  • 清除你的函數to_string使用std庫提供的函數並避免衝突。
  • 然後在需要時使用.c_str()將std :: string轉換爲char *。
  • 刪除無用包括

最終代碼:

#include<iostream> 

using namespace std; 

int main() 
{ 
    FILE *fp; 
    int i=0; 
    string fileName; 
    string name1 = "input"; 
    string name2 = ".txt"; 

    while(i <= 7) 
    { 
    fileName = name1 + to_string(i).c_str() + name2; 
    cout << fileName << "\n"; 
    fp=fopen(fileName.c_str(),"r"); 
    i++; 
    } 

} 
0

只需使用std::ofstream代替混合C和C++。

int main() 
{ 
    string file_name{ "input" }; 
    string extention{ ".txt" }; 

    for (int i{}; i != 8; ++i) { 
     string temp_file_name{ file_name + to_string(i) + extention }; 
     ofstream file{ temp_file_name }; 
    } 
} 
+0

這是什麼類型的語法,用花括號初始化?另外,OP的代碼不對,不是因爲他沒有使用'ofstream'。 – mbaitoff

+1

@mbaitoff它被稱爲[統一初始化](http://programmers.stackexchange.com/a/133690)。 –