C++ 在行尾停止 while 循环(输入 Key)

C++ Stop while loop at the end of the line (enter Key)

任务: 创建程序以读取给定的文本文件并将包含给定子字符串的所有行打印到另一个文本文件中。从文件中读取应该逐行执行。

我的代码:

#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 的地方停止。

第二题: 字符串的处理不是从文本的开头开始。

问题是您正在逐字阅读。流使用“\n”作为标记分隔符。因此在单词阅读过程中它会被忽略。使用getline标准函数获取一行。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main(){
    string inputFileName = "inputFile.txt";
    string outputFileName = "outputFile.txt";

    fstream inputfile;
    ofstream outputFile; 

    inputfile.open(inputFileName.c_str());
    outputFile.open(outputFileName.c_str());

    string keyWord = "morning";
    string line;
    while (std::getline(file, line)) {
        // Processing from the beginning of each line.
        if(line.find(keyWord) != string::npos)
            outputFile << line << "\n";
    }
}

Read file line by line using ifstream in C++

中的答案中得到灵感