为什么这不会更改.txt文件? [英] Why doesn't this change the .txt file?

查看:122
本文介绍了为什么这不会更改.txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

[已解决]

代码:

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


推荐答案

流导致错误。循环终止后检查 f.bad() f.eof()恐怕您有两种选择:

Reading and writing on the same stream results in an error. Check f.bad() and f.eof() after the loop terminates. I'm afraid that you have two choices:


  1. 读取和写入不同的档案

  2. 将整个文件存入内存,并将其关闭并覆盖原来的

As Anders 说,你可能不想使用运算符<< 因为它会打破一切由空格。您可能希望 std :: getline() 在行中。。将它们拖入 std :: vector< std :: string> ,关闭文件,编辑向量并覆盖该文件。

As Anders stated, you probably don't want to use operator<< for this since it will break everything up by whitespace. You probably want std::getline() to slurp in the lines. Pull them into a std::vector<std::string>, close the file, edit the vector, and overwrite the file.

Anders 是正确的钱与他的描述。将文件视为字节流。如果您要将文件正确转换,请尝试类似以下内容:

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:

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;
 }

这个代码有一些小问题, -DOS风格的文本文件,但你可能想出如何解决这个问题,如果你必须。

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.

这篇关于为什么这不会更改.txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆