There is no easier way to get to the end of the line marker, but you could save some time by storing what you read as you read your data. The you would not need to go back, and your loop will be very fast.
Create a character array of size n
, and use it as a circular buffer: when you get to the end of the array, just circle back to its beginning. Store the character in the next position of your circular buffer.
When you detect '\n'
, your buffer contains the n
prior characters, only slightly out of order: the prefix starts at your buffer pointer and goes to the end of the buffer, and the suffix starts at zero and goes to your buffer pointer minus one.
Here is an example of how you can make it work (assuming n
== 20):
int main()
{
ifstream fs("c:\\temp\\a.txt");
char buf[20];
int bp = 0;
bool circular = false;
while (fs.good()) {
char ch = fs.get();
if (ch != '\n') {
buf[bp] = ch;
bp = (bp+1) % 20;
circular |= !bp;
} else {
string s;
if (circular) {
s = string(buf+bp, buf+20) + string(buf, buf+bp);
} else {
s = string(buf, buf+bp);
}
cerr << s << endl;
circular = false;
bp = 0;
}
}
return 0;
}