【发布时间】:2018-10-14 22:14:31
【问题描述】:
我正在尝试编写一个程序,它可以打开一个文本文件,找到某个字符串并将其替换为另一个字符串,然后将更改后的文本写入输出文件。
这是我迄今为止编写的代码。它工作正常,除了输出文件缺少空格和换行符。
我需要保留所有空格和换行符。我该怎么做?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string search = "HELLO"; //String to find
string replace = "GOODBYE"; //String that will replace the string we find
string filename = ""; //User-provided filename of the input file
string temp; //temp variable for our loop to hold the characters from the file stream
char c;
cout << "Input filename? ";
cin >> filename;
ifstream filein(filename); //File to read from
ofstream fileout("temp.txt"); //Temporary file
if (!fileout || !filein) //if either file is not available
{
cout << "Error opening " << filename << endl;
return 1;
}
while (filein >> temp) //While the stream continues
{
if (temp == search) //Check if the temp variable has captured the string we are looking for
{
temp = replace; //When we found the string, we substitute it with the replacement string
}
fileout << temp; //Dump everything to fileout (our temp.txt file)
}
//Close our file streams
filein.close();
fileout.close();
return 0;
}
更新:
我听从了您的建议并执行了以下操作,但现在它根本不起作用(之前的代码运行良好,除了空格)。你能告诉我我在这里做错了什么吗? 谢谢。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string search = "or"; //String to find
string replace = "OROROR"; //String that will replace the string we find
string filename = ""; //User-provided filename of the input file
string temp = ""; //temp variable for our loop to hold the characters from the file stream
char buffer;
cout << "Input filename? ";
cin >> filename;
ifstream filein(filename); //File to read from
ofstream fileout("temp.txt"); //Temporary file
if (!fileout || !filein) //if either file is not available
{
cout << "Error opening " << filename << endl;
return 1;
}
while (filein.get(buffer)) //While the stream continues
{
if (buffer == ' ') //check if space
{
if (temp == search) //if matches pattern,
{
temp = replace; //replace with replace string
}
}
temp = string() + buffer;
for (int i = 0; temp.c_str()[i] != '\0'; i++)
{
fileout.put(temp.c_str()[i]);
}
return 0;
}
}
【问题讨论】:
-
从流中提取标记默认会跳过空格。您需要手动添加它们。此外,如果您不重新打开流,则调用
close()是多余的。std::fstream的析构函数为你做这些 -
就 close() 而言,我们的教授一直在做。至于添加空格,如果它不仅跳过空格,而且还有新行,我该如何手动添加它们。我怎么知道是否添加空格换行符?
-
换行符也是空格。我正在研究下面的答案。应该在 5 分钟内准备好
-
如果我们不使用close(),她会直接扣分。
-
似乎 Sam 先发布了他的答案。这是一个很好的。至于你的老师——你可能想冷静地告诉她,RAII 已经成为
C++的一部分 20 多年了,也许她想升级她的知识以匹配上一个千年末的知识。只是说
标签: c++ file visual-c++ io