I’m trying to edit a text file to remove the vowels from it and for some reason nothing happens to the text file. I think it may be because a mode argument needs to be passed in the filestream.
[SOLVED]
Code:
#include "std_lib_facilities.h"
bool isvowel(char s)
{
return (s == 'a' || s == 'e' || s =='i' || s == 'o' || s == 'u';)
}
void vowel_removal(string& s)
{
for(int i = 0; i < s.length(); ++i)
if(isvowel(s[i]))
s[i] = ' ';
}
int main()
{
vector<string>wordhold;
cout << "Enter file name.\n";
string filename;
cin >> filename;
ifstream f(filename.c_str());
string word;
while(f>>word) wordhold.push_back(word);
f.close();
ofstream out(filename.c_str(), ios::out);
for(int i = 0; i < wordhold.size(); ++i){
vowel_removal(wordhold[i]);
out << wordhold[i] << " ";}
keep_window_open();
}
Reading and writing on the same stream results in an error. Check
f.bad()andf.eof()after the loop terminates. I’m afraid that you have two choices:As Anders stated, you probably don’t want to use
operator<<for this since it will break everything up by whitespace. You probably wantstd::getline()to slurp in the lines. Pull them into astd::vector<std::string>, close the file, edit the vector, and overwrite the file.Edit:
Anders was right on the money with his description. Think of a file as a byte stream. If you want to transform the file in place, try something like the following:
There are some small problems with this code like it won’t work for MS-DOS style text files but you can probably figure out how to account for that if you have to.