OK, the eventual goal of my project is a kind of word insert/delete/replace. You read a file... "The quick brown fox jumps over the lazy dog." and you can delete all instances of "fox", replace "fox" with "cat", insert "giraffe" wherever you want, etc. Word processing stuff.
So I figured I'd have a big file and start reading it into a stream, parse that stream, then do whatever (replace, add, delete). Except I can't seem to get that far since it breaks with my simple little "insert" experiment program. The program below starts with a stream...
abcdefghijkmnopqr
The goal is to end up with this stream...
abcdefgzzzhijkmnopqr
What I get is this...
zzzdefghijkmnopqr
So I have at least two problems.
- "zzz" is being written at position 0, not position 7. Note the 7 in line 33.
- "zzz" overwrites the characters in the stream. It doesn't insert.
Code is below. I'd like to know
- What I'm doing wrong.
- Is this (manipulating iostreams) a decent approach to the whole problem?
#include <iostream>
#include <sstream>
#include <cassert>
using namespace std;
void PrintStream(iostream& stream)
{
int startPos = stream.tellg();
assert(stream.good());
cout << "Start position = " << startPos << endl;
char c;
while(stream.good())
{
c = stream.get();
if(stream.good())
{
cout << c;
}
}
cout << endl;
stream.clear();
stream.seekg(startPos);
assert(stream.good());
}
void Manipulate(iostream& stream)
{
stream.seekg(7, ios_base::beg);
assert(stream.good());
stream.write("zzz", 3);
assert(stream.good());
}
int main()
{
string aString = "abcdefghijkmnopqr";
stringstream stream(aString);
stream.seekg(0, ios_base::beg);
assert(stream.good());
PrintStream(stream);
Manipulate(stream);
stream.seekg(0, ios_base::beg);
assert(stream.good());
PrintStream(stream);
cin.get();
return 0;
}
Note. All "assert" statements succeed. Actual program output is the following.
Start position = 0
abcdefghijkmnopqr
Start position = 0
zzzdefghijkmnopqr