gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:23:35 24 4
gpt4 key购买 nike

我的任务是在 .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;
}
}

最佳答案

您面临的错误尚不清楚,但我可以看到一个大问题,您在空字符串上运行 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';
}

关于用于查找和修改/替换 .c 文件中的字符串的 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35884125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com