- ベストアンサー
空白を含む文をファイルに書き込んで10文字ずつ読み出す
空白を含む文を10文字ずつ読み出そうとしています。でも 文1:I am a poor programmer. 文2:2nd Sentence 結果:2nd Sentenr programmer. となります。"I am a poo"が欲しいのですが。 800文字以内にするためにmainだけにしました。後で補足できます。 int main() { sentence sntc; fstream file; file.open("SENTENCE.TXT", ios::app | ios::out | ios::in | ios::binary ); sntc.getData(); file.write( reinterpret_cast<char*>(&sntc), sizeof(sntc) ); file.seekg(0, ios::end); int endposition = file.tellg(); int n = endposition / sizeof(sentence); cout << "\nThere are " << n << " sentences in file"; cout << "\nEnter sentence number: "; cin >> n; int position = (n-1) * sizeof(sentence); file.seekg(position); file.read( reinterpret_cast<char*>(&sntc), sizeof(sntc) ); sntc.showData(); cout << endl; file.seekg(position, ios::cur); file.read( reinterpret_cast<char*>(&sntc), 10); sntc.showData(); cout << endl; return 0; }
- みんなの回答 (3)
- 専門家の回答
お礼
解決しました! 一つ目の問題は私の「テストで表示」がいけなかったみたいです。 あの行のお陰で「本番の表示」のときには既に駒が一つ進んでました。 二つ目の問題はどうも // file.seekg(position, ios::cur); の行が邪魔をしていたようです。 下の通りに修正しました。 int main() { sentence sntc; fstream file; file.open("SENTENCE.TXT", ios::app | ios::out | ios::in | ios::binary ); sntc.getData(); file.write( reinterpret_cast<char*>(&sntc), sizeof(sntc) ); file.seekg(0, ios::end); int endposition = file.tellg(); int n = endposition / sizeof(sentence); cout << "\nThere are " << n << " sentences in file"; cout << "\nEnter sentence number: "; cin >> n; int position = (n-1) * sizeof(sentence); file.seekg(position); for(int i=0; i<5; i++) { position = file.tellg(); cout << position; // file.seekg(position, ios::cur); file.read( reinterpret_cast<char*>(&sntc), 10); sntc.showData(); cout << endl; } return 0; } オリジナルの文は "I am on my way to becoming a great C++ programmer."で 結果はこんな風です。 0 Sentence: I am on myB 10 Sentence: way to beB 20 Sentence: coming a gB 30 Sentence: reat C++ pB 40 Sentence: rogrammer.B Press any key to continue (Bがついていますが…気にしないでください(~o~)) 結局、readとreinterpret_cast<char*>はそのままなのですが getlineの発想から何がおかしいか発見できました。 liar_adanさんの回答がなかったらここまで辿り着けなかったと思います。 なるべく自分で解くように努力しますが、躓くだろうことは必至ですから これからもどうかよろしくお願いします。m(__)m ありがとうございました。