【发布时间】:2021-05-07 14:39:14
【问题描述】:
我有一个包含以下数据的 txt 文件 (inputFile.txt):
Start
FX
FX
FX
FX
End
我想要实现的是将 FX 替换为 TL 和 BQ 以便我都重复 4 次外汇数量。见下文(预期结果 - outputFile.txt):
Start
TL
TL
TL
TL
BQ
BQ
BQ
BQ
End
但是,在我当前的实现中,我有以下(当前结果):
Start
TL
BQ
TL
BQ
TL
BQ
TL
BQ
End
以下是我当前的代码:
void replaceInFile(string inputFile, string outFile)
{
string toBeReplaced = "FX";
string toReplaceWith1 = "TL";
string toReplaceWith2 = "BQ";
ifstream inputStream(inputFile);
ofstream outputStream(outFile);
if (!inputStream.is_open() || !outputStream.is_open())
{
cerr << "Either open input or output file failed!";
}
string line;
string duplicateLine;
size_t len = toBeReplaced.length();
while (getline(inputStream, line))
{
duplicateLine = line;
for (size_t pos = line.find(toBeReplaced); pos != string::npos; pos = line.find(toBeReplaced, pos))
{
if (pos)
{
line.replace(pos, toBeReplaced.length(), toReplaceWith1);
duplicateLine.replace(pos, toBeReplaced.length(), toReplaceWith2);
// This line creates the duplicate
outputStream << duplicateLine << endl;
}
}
outputStream << line << endl;
}
inputStream.close();
outputStream.close();
}
如何修改上面的代码得到预期的结果/outputFile.txt?
【问题讨论】:
-
计数
FX并打印TL和BQ的对应数量?如果存在FX以外的东西怎么办?其他选择是看不到inputFile.txt,如果输入是固定且已知的,则只打印所需的输出。 -
@MikeCAT 对不起,我不明白你的评论。
标签: c++ c++11 file-manipulation