如何使用 C++ 编辑文本文件中的一行? [复制]

2024-03-05

我有一个这样的txt文件:

"shoes":12
"pants":33
"jacket":26
"glasses":16
"t-shirt":182

我需要更换夹克的数量(例如从 26 到 42)。所以,我编写了这段代码,但我不知道如何编辑包含“jacket”一词的特定行:

#include <iostream>
#include <fstream> 

using namespace std;

int main() {

    ifstream f("file.txt");
    string s;

    if(!f) {
        cout< <"file does not exist!";
        return -1;
    }

    while(f.good()) 
    {       
        getline(f, s);
        // if there is the "jacket" in this row, then replace 26 with 42.
    }


    f.close(); 
    return 0;
}

为了修改文本文件中的数据,您通常必须阅读 将整个文件写入内存,在那里进行修改,然后重写 它。在这种情况下,我建议为条目定义一个结构, 和name and quantity条目,平等定义为平等 名称和重载operator>> and operator<<读写 从文件中获取。然后你的整体逻辑将使用如下函数:

void
readData( std::string const& filename, std::vector<Entry>& dest )
{
    std::ifstream in( filename.c_str() );
    if ( !in.is_open() ) {
        //  Error handling...
    }
    dest.insert( dest.end(),
                 std::istream_iterator<Entry>( in ),
                 std::istream_iterator<Entry>() );
}

void
writeData( std::string const& filename, std::vector<Entry> const& data )
{
    std::ifstream out( (filename + ".bak").c_str() );
    if ( !out.is_open() ) {
        //  Error handling...
    }
    std::copy( data.begin(), data.end(), std::ostream_iterator<Entry>( out ) );
    out.close();
    if (! out ) {
        //  Error handling...
    }
    unlink( filename.c_str() );
    rename( (filename + ".bak").c_str(), filename.c_str() );
}

(我建议在错误处理中引发异常,这样你就不会 必须担心的其他分支ifs。除了 的创建ifstream在第一种情况下,错误条件是例外的。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 C++ 编辑文本文件中的一行? [复制] 的相关文章

随机推荐