如何读取 .txt 将内容复制到另一个 .txt 通过使用 fstream 到类似的内容。
问题是,当文件中有新行时。使用 ifstream 时如何检测?
用户输入“苹果”
例如:
note.txt =>
我昨天买了一个苹果。
苹果味道鲜美。
note_new.txt =>
我昨天买了一个。
味道鲜美。
结果笔记假设在上面,而是:
note_new.txt =>
我昨天买了一个。味道鲜美。
如何检查源文件中是否有新行,它也会在新文件中创建新行。
这是我当前的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile ("note.txt");
string word;
ofstream outFile("note_new.txt");
while(inFile >> word) {
outfile << word << " ";
}
}
你们都可以帮我吗?实际上,我还检查检索的单词何时与用户指定的单词相同,然后我不会将该单词写入新文件中。因此,一般来说,它将删除与用户指定的单词相同的单词。
最佳答案
逐行方法
如果您仍然想逐行执行,可以使用 std::getline()
:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile ("note.txt");
string line;
// ^^^^
ofstream outFile("note_new.txt");
while( getline(inFile, line) ) {
// ^^^^^^^^^^^^^^^^^^^^^
outfile << line << endl;
}
}
它从流中获取一行,你只需在任何你想要的地方重写它。
更简单的方法
如果您只想在另一个文件中重写一个文件,请使用
rdbuf
:#include <fstream>
using namespace std;
int main() {
ifstream inFile ("note.txt");
ofstream outFile("note_new.txt");
outFile << inFile.rdbuf();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
}
编辑: 它将允许删除您不想出现在新文件中的单词:
我们使用
std::stringstream
:#include <iostream>
#include <fstream>
#include <stringstream>
#include <string>
using namespace std;
int main() {
ifstream inFile ("note.txt");
string line;
string wordEntered("apple"); // Get it from the command line
ofstream outFile("note_new.txt");
while( getline(inFile, line) ) {
stringstream ls( line );
string word;
while(ls >> word)
{
if (word != wordEntered)
{
outFile << word;
}
}
outFile << endl;
}
}