C++ replace word in file with equally long not replacing last word

时间:2016-10-15 16:59:04

标签: c++ file fstream

I'm trying to replace every occurrence of a word in a file with '*'-s, equally long as the word. This is my code so far:

fstream file("example.txt");
string desiredWord;
cin >> desiredWord;
string replacement(desiredWord.size(), '*'); 
string word;

while(file >> word) {
    if (word == desiredWord) {
        file.seekp(-(int)desiredWord.size(), ios::cur);
        file << replacement;
    }
}
file.close();

And it seems to work in all cases except when the desired word is the last one in the file not followed by any character, it gets into the if clause but the writing part doesn't seem to do anything. Any suggestions why it's happening and how to fix it? Thanks in advance.

0 个答案:

没有答案