muh*_*san 4 c++ file-io fstream
如何通过将fstream用于类似的内容来读取.txt将内容复制到另一个.txt.问题是,在文件中有新行.使用ifstream时如何检测?
用户输入"apple"
例如: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 << " ";
}
}
Run Code Online (Sandbox Code Playgroud)
你能帮助我吗?实际上,我还会检查检索到的单词与用户指定的单词是否相同,然后我不会在新文件中写入该单词.所以一般来说,它会删除与用户指定的单词相同的单词.
如果您仍希望逐行执行此操作,则可以使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
它从流中获取一行,您只需在任何地方重写它.
如果您只想在另一个文件中重写一个文件,请使用rdbuf:
#include <fstream>
using namespace std;
int main() {
ifstream inFile ("note.txt");
ofstream outFile("note_new.txt");
outFile << inFile.rdbuf();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)
编辑:它将允许删除您不想在新文件中的单词:
我们使用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;
}
}
Run Code Online (Sandbox Code Playgroud)