为什么不改变.txt文件?

时间:2009-07-28 00:30:15

标签: c++

我正在尝试编辑文本文件以从中删除元音,并且由于某种原因,文本文件没有任何反应。我想这可能是因为模式参数需要在文件流中传递。

[解决]

代码:

#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();
}

3 个答案:

答案 0 :(得分:4)

在同一个流上读取和写入会导致错误。循环终止后检查f.bad()f.eof()。我担心你有两个选择:

  1. 读取和写入不同的文件
  2. 将整个文件读入内存,关闭它并覆盖原始文件
  3. 正如Anders所述,您可能不希望使用operator<<,因为它会通过空格来破坏所有内容。您可能希望std::getline()在行中啜饮。将它们拉入std::vector<std::string>,关闭文件,编辑矢量,然后覆盖文件。

    编辑:

    Anders对他的描述是正确的。将文件视为字节流。如果要将文件转换为,请尝试以下操作:

    void
    remove_vowel(char& ch) {
        if (ch=='a' || ch=='e' || ch=='i' || ch =='o'  || ch=='u') {
            ch = ' ';
        }
    }
    
    int
    main() {
        char const delim = '\n';
        std::fstream::streampos start_of_line;
        std::string buf;
        std::fstream fs("file.txt");
    
        start_of_line = fs.tellg();
        while (std::getline(fs, buf, delim)) {
            std::for_each(buf.begin(), buf.end(), &remove_vowel);
            fs.seekg(start_of_line);     // go back to the start and...
            fs << buf << delim;          // overwrite the line, then ...
            start_of_line = fs.tellg();  // grab the next line start
        }
        return 0;
     }
    

    此代码存在一些小问题,例如它不适用于MS-DOS样式的文本文件,但如果必须,您可能会弄清楚如何解释。

答案 1 :(得分:2)

文件有点像列表,顺序字节流。当您打开文件时,您将文件指针放在最开始位置,每次读/写都会重新定位文件中的文件指针,其偏移量大于最后一个。您可以使用seekg()移回文件并覆盖以前的内容。上面你的方法的另一个问题是,通常在一个或多个空格之间可能存在一些分隔符,例如,你也需要处理它们的读/写。

将整个文件加载到内存中并对该字符串进行操作然后重写整个文件要容易得多。

答案 2 :(得分:0)

你确定你的while循环实际上正在执行吗?尝试添加一些调试输出以验证它是否正在按照您的想法进行操作。

相关问题