自己解決はしたのですが、どうしても納得いかないことがあるのでわかる方説明お願いします。
ゲームスコアの記録、表示のためにファイル入出力のプログラムを作成したのですが、以下のコードで
test□□□□ cェ
100
といったような出力がされます
#include <fstream>
#include <iostream>
using namespace std;
/* ファイル読み書きテスト */
int main(){
fstream out("testFile.txt",fstream::out, fstream::binary);
/* 書き込みテスト */
char* testStr_o = "test";
int testInt_o = 100;
out.write( testStr_o,sizeof(testStr_o) );
out.write( reinterpret_cast< char* >(&testInt_o), sizeof(int) );
out.close();
/* 読み込みテスト */
fstream in("testFile.txt",fstream::in, fstream::binary);
char* testStr_i = new char[4];
int testInt_i;
in.read(testStr_i,sizeof(testStr_i));
in.read(reinterpret_cast< char* >(&testInt_i),sizeof(int));
cout << testStr_i << endl;
cout << testInt_i;
in.close();
}
test
100
と表示され、問題はなくなりました。
(前のコードとの違いは18,21行です)
#include <fstream>
#include <iostream>
using namespace std;
/* ファイル書き込みテスト */
int main(){
fstream out("testFile.txt",fstream::out, fstream::binary);
/* 書き込みテスト用 */
char* testStr_o = "test";
int testInt_o = 100;
out.write( testStr_o,sizeof(testStr_o) );
out.write( reinterpret_cast< char* >(&testInt_o), sizeof(int) );
out.close();
/* 読み込みテスト用 */
fstream in("testFile.txt",fstream::in, fstream::binary);
char* testStr_i = new char[5];
int testInt_i;
in.read(testStr_i,sizeof(testStr_i));
testStr_i[4] = '\0';
in.read(reinterpret_cast< char* >(&testInt_i),sizeof(int));
cout << testStr_i << endl;
cout << testInt_i;
in.close();
}
いままで考えて来なかったのですがそもそも何故char*終端にnull文字を入れないと化けるのか、という2点が納得いかないので、
このことについてわかる方教えていただきたいです。長くなってしまいましたが以上です。