std::string reg = ("AA00 AAA");
// Open the file for reading
std::ifstream file_in("../data/history/" reg ".his");
// populate vector with line string from file
std::vector<std::string> contents;
int i;
std::string line;
while(!file_in.eof( )) {
std::getline(file_in, line);
contents.emplace_back(line);
i ;
}
// specify phrases for replacement
std::string toReplace(" NA ");
std::string dateStamp = dateHelpers::getCurrentDate();
//initialize aux container
std::vector<std::string> newLineVec;
//perform replacment
std::for_each(contents.begin(), contents.end(),[dateStamp](auto line){ // << was capturing newLineVec Here.
int index;
std::cout << "Initial String :" << line << std::endl;
while((index = line.find("NA")) != std::string::npos) { //for each location where phrase is present
line.replace(index, dateStamp.length(), dateStamp); //remove & replace at that position
std::cout << "Final String :" << line << std::endl;
// newLineVec.emplace_back(line); // store results ???
}
}
);
My goal is to search & replace instances of word in a text file. I can not seem to use the result of the for each to populate a container to then stream back to the input file. Is my approach here sensible or am I way off track?
Any help would be greatly appreciated. I've tried to make the snippet minimally reproducible so any input on how I could improve my question asking would also go a long way.
Edit* output example ..
Initial String :james smith 88 broad lane 07474493221 2021/05/12 NA
Final String :james smith 88 broad lane 07474493221 2021/05/12 2022/12/14
Initial String :adam brown 42 church street 07392834769 2022/03/03 NA
Final String :adam brown 42 church street 07392834769 2022/03/03 2022/12/14
Initial String :James smith 88 broad lane 07474493221 2022/09/12 NA
Final String :James smith 88 broad lane 07474493221 2022/09/12 2022/12/14
CodePudding user response:
there is no need to store the data in a container, you can read each line, replace your pattern-string with your replacement-string and output it in a single loop.
here is pseudo-code
open input file
while (not end of file)
{
read 1 line
if pattern in line, then replace it
print output
}
CodePudding user response:
If you want to store data in "newLineVec" in your Lambda, then you need to make it accessible.
The easiest way is to hand in all outer scope variables into the Lamda using references in the lambdas' closure.
Simply write:
std::for_each(contents.begin(), contents.end(),[&](auto line){
Then you can use all variables.