如何使用C ++编辑文本文件中的行? [英] How to edit a row in a text file with C++?

查看:169
本文介绍了如何使用C ++编辑文本文件中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的txt档案:

I have a txt file like this:

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

我需要更换夹克的数量(例如从26到42)。所以,我写了这段代码,但我不知道如何编辑一个具体的行夹克:

I need to replace the number of jacket ( from 26 to 42 for example ). So, I have wrote this code, but I don't know how to edit a specific row where there is the word "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;
}


推荐答案

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

In order to modify data in a text file, you'll generally have to read the entire file into memory, make the modifications there, then rewrite it. In this case, I'd suggest defining a structure for the entries, with name and quantity entries, equality defined as equality of the names, and an overloaded operator>> and operator<< to read and write it from the file. You're overall logic would then use functions like:

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

(我建议在错误处理中提出异常, 't
必须担心 if 的其他分支。除了
创建 ifstream 在第一个,错误条件是例外。)

(I'd suggest raising exceptions in the error handling, so that you don't have to worry about the else branches of the ifs. Except for the creation of the ifstream in the first, the error conditions are exceptional.)

这篇关于如何使用C ++编辑文本文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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