用于查找和修改/替换.c文件中的字符串的C ++代码

时间:2016-03-09 06:03:39

标签: c++ c file-handling

我的任务是在.c文件中搜索字符串并使用c ++代码修改它。我做了直到搜索字符串,但修改它是一个错误。如果我将c文件的内容复制到文本文件并尝试修改它,它会给出相同的错误。所以我确定我的代码有问题。作为初学者,请帮忙。提前致谢。 我的代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string s1, s2;

  ifstream test("test.csv");

  while (test.eof()==0)      //test.eof() returns 0 if the file end is not reached
  {
    getline(test, s1, ',');     //reads an entire line(row) till ',' to s1

    getline(test, s2, '\n');

    cout << s1 + "= " +s2 << endl;

    fstream fileInput;

    int offset;

    string line;

    string search=s1;

    fileInput.open("IO_CAN_0_User.c");

if(fileInput.is_open()) {

    while(!fileInput.eof()) {

        getline(fileInput, line);

        if ((offset = line.find(search, 0)) != string::npos) {

            cout << "found: " << search << endl;
            string str;
            str=search;
            str.replace(str.begin()+25,str.begin()+31,"=s2  //");
            break;
        }

    }
    //cout << "string not found" << endl;
    fileInput.close();
}
else cout << "Unable to open file.";


if(test.eof()!=0)
    cout<<"end of file reached"<<endl;
    getchar();
    return 0;
  }
}

1 个答案:

答案 0 :(得分:1)

您所面临的错误并不明确,但我可以看到一个大问题,即您在空字符串上运行replace

您的代码:

string str;
search=str;
str.replace(str.begin()+25,str.begin()+31,"=s2  //");

您创建str(默认初始化为空字符串),将其分配给search(因此此字符串变为空)然后您调用replace尝试从char 25更改为31,由于str为空,因此不存在。

<强>更新
可能你需要修复替换,但是你不能指望文件改变:你正在修改的字符串在内存中,而不是文件的一部分。

因此我会更改代码(尽可能使用你的代码):
 *添加输出文件
 *修理替换件  *保存输出文件的每一行(如果需要,替换

fileInput.open("IO_CAN_0_User.c");
ofstream  fileOutput;
fileOutput.open("output.c");

if(fileInput.is_open() && fileOutput.is_open() ) {

  while(!fileInput.eof()) {

    getline(fileInput, line);

    if ((offset = line.find(search, 0)) != string::npos) {

        cout << "found: " << search << endl;

        line.replace( offset, offset+search.size(), s2 );
    }

    fileOutput << line << '\n';
}