首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何替换CSV文件中的值

如何替换CSV文件中的值
EN

Stack Overflow用户
提问于 2014-09-15 19:04:41
回答 1查看 1.8K关注 0票数 0

我的CSV文件构建如下:

代码语言:javascript
复制
1;name;2;5;
2;diff_name;3;5;

在阅读下一行之前,我希望能够将5替换为2。所以我正在读这个文件:

代码语言:javascript
复制
file>>number1;
file.ignore( numeric_limits < streamsize >::max(), ';' );
file>>data;

诸若此类。我试着这样写:

代码语言:javascript
复制
long pos = plik.tellp();
plik.seekp (pos-2);
plik<<other_number;

但它破坏了文件。我不知道是怎么回事,但这并不可靠。pos以某种方式依赖于文件长度,我不能让它每次都这样工作(在文件中使用不同的值)。有没有其他方法来替换这里的值?有什么简单的方法吗?

EN

回答 1

Stack Overflow用户

发布于 2014-09-15 20:50:23

正如Joachim Pileborg在评论中所说的,你不能真的(简单地)直接替换文件中的内容。解决方案是在另一个文件中写入。如果你的第一个文件足够小,你可以使用你的内存来代替第二个文件,并将结果写入第一个文件。

我的代码:

代码语言:javascript
复制
#include <fstream>
#include <iostream>
using namespace std;

int main(){
  ifstream ifile("file.csv"); //First file
  ofstream ofile("filenew.csv"); //File with replaced fields
  char s[100];
  string temp;//useful for the replacement
  int count=0;//fields counter (useful for replacement)
  while(ifile.good()){
    ifile.getline(s, 100, ';'); //We read the file field by field
    count++;
    if(ifile.good()){
      if(count==3){ //The third field is stored in a temp variable
        temp = s;
      }
      else if(count==4){//And we put the fourth field before the third
        ofile << s;
        ofile << ';';
        ofile << temp;
        ofile << ';';
        count=0;
      }
      else{
        if(count==5)count=0;
        ofile << s;
        ofile << ';';
      }
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25846626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档