为什么我可以替换文本文件中的一个单词,而不能替换另一个单词

Why can I replace one word in a text file but not another?

本文关键字:单词 替换 一个 另一个 不能 文本 我可以 文件 为什么      更新时间:2023-10-16

我正在逐字逐句地阅读下面的文本文件,替换单词"@name@"answers"@festival@"。我的程序非常适用于@name@,但只更改了第一个"节日",而没有更改第二个。我不知道为什么。

John Doe

房间213-A

通用老建筑

信息技术学院

编程州立大学

纽约州纽约市12345-0987

美国

收件人:@name@

主题:节日问候:@festival@

尊敬的@name@,

祝你和你的家人节日快乐!

您的真诚,

约翰·

void Main::readFile()
{
while (v.size() != 0) {
    string name;
    name = v.at(v.size()-1);
    v.pop_back();
    std::ofstream out(name + ".txt");
    ifstream file;
    file.open("letter.txt");
    string word;
    string comma;
    char x;
    word.clear();
    while (!file.eof())
    {
        x = file.get();
        while (x != ' ' && x != std::ifstream::traits_type::eof())
        {
            if (word == "@name@") {
                word = name;
            }
            if (word == "@festival@") {
                word = "THISISATEST!!!!!!!!!!!!!!";
            }
            word = word + x;
            x = file.get();
        }
        out << word + " ";
        word.clear();
    }
}

问题是内部while条件,如果在@festival@之后存在' ',则问题将不成立。以下代码是正确的

void Main::readFile()
{
while (v.size() != 0) {
    string name;
    name = v.at(v.size()-1);
    v.pop_back();
    std::ofstream out(name + ".txt");
    ifstream file;
    file.open("letter.txt");
    string word;
    string comma;
    char x;
    word.clear();
    while (!file.eof())
{
    x = file.get();
    while (x != ' ' && x != std::ifstream::traits_type::eof())
    {
        if (word == "@name@") {
            word = name;
        }
        if (word == "@festival@") {
            word = "THISISATEST!!!!!!!!!!!!!!";
        }
        word = word + x;
        x = file.get();
    }
    if (word == "@name@") {
          word = name;
    }
    if (word == "@festival@") {
        word = "THISISATEST!!!!!!!!!!!!!!";
    }
    out << word + " ";
    word.clear();
    }
}

首先,请参阅为什么循环条件中的iostream::eof被认为是错误的?

这不是一个优雅的解决方案。。。但这是对原始代码的更好改进。(我让你想想更有效的解决方案):

void Main::readFile()
{
while (v.size() != 0) {
    string name;
    name = v.at(v.size()-1);
    v.pop_back();
    std::ofstream out(name + ".txt");
    ifstream file;
    file.open("letter.txt");
    string festival = "THISISATEST!!!";
    string line, nameHolder = "@name@", festivalHolder = "@festival@";
    while (std::getline(file, line))
    {
        std::size_t n_i = line.find(nameHolder);
        if(n_i != std::string::npos)
            line.replace(n_i, nameHolder.size(), name);
        std::size_t f_i = line.find(festivalHolder);
        if(f_i != std::string::npos)
            line.replace(f_i, festivalHolder.size(), festival);
        out << line << 'n';
    }
}