2016-09-26 14 views
2

ループ内にファイル名を作成するためのC++コードを記述しました。次のように私のサンプルコードがある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++; 
    } 

} 

しかし、私は、コードを実行したとき、私は取得しています例えば、私は次のように8回のループを実行し、8つのテキストファイルを作成します。次のエラー:

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()は、std::stringでなく、const char*をパラメータとする。文字列のconst char*を取得するには、.c_str()関数を使用します。

fopen()はc-apiですが、代わりに、C++のファイルストリームを使用することもできます。

は読み取り/書き込み、std::ifstreamは入力のみです。 std::ofstream出力専用です。

1
  • stdライブラリによって提供されたものを使用し、競合を避けるためにto_string関数を消去します。
  • 次に、std :: stringを必要に応じて.c_str()を使用して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

ちょうどCとC++を混合するのではなく、std::ofstreamを使用します。

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

これはどのような構文ですか、中括弧で初期化しますか?また、彼は 'ofstream'を使用していないので、OPのコードは間違っていません。 – mbaitoff

+1

@mbaitoffこれは[統一初期化](http://programmers.stackexchange.com/a/133690)と呼ばれています。 –

関連する問題