【发布时间】:2014-11-06 22:08:23
【问题描述】:
我需要编写一个程序来读取文件中的某些字符。 例如:所有字符从头到尾或倒序排列。如何显示所有字符而不是一个字符?
//This program reads a file from beg to end, end to beg, beg to 4th position,
//8th to 15th position, end to 3rd position, and 22nd to end
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char letter; //holds the character
fstream file("alphabet.txt", ios::in);
file.seekg(5L, ios::beg);
file.get(letter);
cout << "Beginning to the 4th letter: " << letter << endl;
file.seekg(-22L, ios::end);
file.get(letter);
cout << "21st letter to the end: " << letter << endl;
file.close();
system("pause");
return 0;
}
【问题讨论】:
-
你有什么问题?
-
那么问题是什么?
-
如何从头到尾显示所有字符?反之亦然?
-
首先,你为什么在一个不是以二进制模式打开的文件上使用
seekg?由于回车/换行翻译,对以文本模式打开的文件使用 seekg 会让你发疯。 -
我认为您将移动文件指针(从下一个读取的位置)与实际的读取操作(从当前位置读取并将文件指针增加读取的字节数)混淆了。