2016-07-05 20 views
-1

firstFileStream[50]という文字配列があり、これはfstreamを使ってinfileから書き込まれています。C++でchar配列を文字列に変換するにはどうすればよいですか?

この文字配列をfirstFileAsStringという文字列に変換したいとします。 string firstFileAsString = firstFileStream;を書くと、配列内の最初の単語だけが書き込まれ、最初のスペースまたは空の文字で停止します。私がfirstFileAsString(firstFileStream)と書くと、同じ出力が得られます。

文字配列全体、つまりその中のすべての単語を文字列に書き込むにはどうすればよいですか? zdanが指摘したように、私は、ファイルの最初の言葉を読んでいたので、代わりに私が割り当てるためにistreambuf_iterator<char>を使用しました、

string firstInputFile = "inputText1.txt"; 
char firstFileStream[50]; 

ifstream openFileStream; 
openFileStream.open(firstInputFile); 

if (strlen(firstFileStream) == 0) { // If the array is empty 
    cout << "First File Stream: " << endl; 
    while (openFileStream.good()) { // While we haven't reached the end of the file 
     openFileStream >> firstFileStream; 
    } 
    string firstFileAsString = firstFileStream; 

} 
+0

はどのようにどのように多くの文字をコピーするために知っているのですか? – juanchopanza

+0

入力ファイルは、空白を含むその文字数を含む長さで設定されています – fauliath

+0

@Magis 50文字をコピーする必要がありますか、それとも秘密の番号ですか? – juanchopanza

答えて

0

私の問題を:ここで

はで読み書きするコードです最初に文字配列ではなく文字列に直接コンテンツを挿入します。これは文字配列に分割することができます。

0
openFileStream >> firstFileStream; 

は、ファイルから1単語のみを読み取ります。

(少なくとも緩衝能まで)ファイル全体を読み込むの簡単な例は次のようになります。

openFileStream.read(firstFileStream, sizeof(firstFileStream) - 1); 
// sizeof(firstFileStream) - 1 so we have space for the string terminator 
int bytesread; 
if (openFileStream.eof()) // read whole file 
{ 
    bytesread = openFileStream.gcount(); // read whatever gcount returns 
} 
else if (openFileStream) // no error. stopped reading before buffer overflow or end of file 
{ 
    bytesread = sizeof(firstFileStream) - 1; //read full buffer 
}  
else // file read error 
{ 
    // handle file error here. Maybe gcount, maybe return. 
} 
firstFileStream[bytesread] = '\0'; // null terminate string 
関連する問題