2
我想在指定的文件中查找一行并将其替换为我的行。我没有权限访问我将要运行的计算机上的库,所以我创建了一个自定义文件。麻烦似乎是对fstream对象的写入调用。我想知道你们有没有人可以帮忙。另外,我的getline循环在到达文件末尾之前停止,我不知道为什么。使用fstream写入
#include <iostream>
#include <fstream>
#include <string>
#define TARGET2 "Hi"
using namespace std;
void changeFile(string fileName){
fstream myStream;
myStream.open(fileName.c_str(),fstream::in | fstream::out);
string temp;
string temp2 = "I like deep dish pizza";
while(getline(myStream, temp)){
if(temp == TARGET2){
cout << "Match" << endl;
myStream.write(temp2.c_str(), 100);
myStream << temp2 << endl;
cout << "No runtime error: " << temp2 << endl;
}
cout << temp << endl;
}
myStream.close();
}
int main (void){
changeFile("Hi.txt");
return 0;
}
Hi.txt
Hi
Today is June 18
I like pizza
I like pepperoni
输出是:
Match
No runtime error: I like deep dish pizza
Hi
我因为第二行写两次似乎没有工作。我会尝试stringstream方法,看看它是如何发展的。 –
@BabbuMaan我列举了一个如何做到这一点,以防万一它有用。 –