【发布时间】:2021-09-11 05:44:04
【问题描述】:
任务: 创建程序以读取给定的文本文件并将包含给定子字符串的所有行打印到另一个文本文件中。从文件中读取应该是逐行进行的。
我的代码:
#include <bits/stdc++.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream file; // required for input file further processing
ofstream outputFile;
string word1, word2, t, q, inputFileName;
string keyWord = "morning";
string enterKey = "\n";
inputFileName = "inputFile.txt";
file.open(inputFileName.c_str()); // opening the EXISTING INPUT file
outputFile.open("outputFile.txt"); // CREATION of OUTPUT file
// extracting words from the INPUT file
while (file >> word1){
if(word1 == keyWord) {
while(file >> word2 && word2 != enterKey){
// printing the extracted words to the OUTPUT file
outputFile << word2 << " ";
}
}
}
outputFile.close();
return 0;
}
第一个问题: outputFile 包含整个文本,换句话说,while 循环不会在按下 enter 的地方停止。
第二个问题: 字符串的处理不是从文本的开头开始。
【问题讨论】:
-
尝试
std::getline>>运算符丢弃所有空格,包括换行符 -
快速建议 - 如果您使用的是类 UNIX 系统(例如 Linux、MacOS),您可以使用命令 'cat inputFile.txt | grep morning > outputFile.txt' 得到想要的结果。
-
Alan Birtles,Abdus Khazi,谢谢你们的建议,伙计们!
标签: c++ while-loop printing text-processing