我想打开文件,搜索字符串,替换字符串,然后在最后打印替换后的字符串直到结束。
到目前为止,我已经使用
打开了文件fstream file ("demo.cpp");
使用
while (getline (file,line))
但使用
string.find("something")
总是给我行号0,无论我在 find()
的参数中放入哪个字符串我的问题是,在这种情况下我还可以使用其他内置函数吗?还是我必须手动搜索所有行?
答案 0 :(得分:1)
要获得匹配发生的行号,您必须计算行数:
if (ifstream file("demo.cpp")) {
int line_counter = 0;
string line;
while (getline (file,line) {
line_counter++;
if (line.find("something") != string::npos) {
cout << 'Match at line ' << line_counter << endl;
}
}
} else {
cerr << "couldn't open input file\n";
}
答案 1 :(得分:0)
您可以在每一行使用此replaceAll function,并将&#34;替换为文件功能&#34;建立在它之上。
我修改它以在发生替换时返回布尔值:
bool replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return false;
size_t start_pos = 0;
bool res = false;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
res = true;
}
return res;
}
然后,剩下的就是:
ReplaceInFile
方法:
void replaceInFile(const std::string& srcFile, const std::string& destFile,
const std::string& search, const std::string& replace)
{
std::ofstream resultFile(destFile);
std::ifstream file(srcFile);
std::string line;
std::size_t lineCount = 0;
// You might want to chech that the files are properly opened
while(getline(file,line))
{
++lineCount;
if(replaceAll(line, search, replace))
std::cout << "Match at line " << lineCount << " " << replace << std::endl;
resultFile << line << std::endl;
}
}
示例:强>
int main()
{
replaceInFile("sourceFile.txt", "replaced.txt", "match", "replace");
return 0;
}