【问题标题】:C++ Stop while loop at the end of the line (enter Key)C++ 在行尾停止while循环(输入Key)
【发布时间】: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 &gt;&gt; 运算符丢弃所有空格,包括换行符
  • 快速建议 - 如果您使用的是类 UNIX 系统(例如 Linux、MacOS),您可以使用命令 'cat inputFile.txt | grep morning > outputFile.txt' 得到想要的结果。
  • Alan Birtles,Abdus Khazi,谢谢你们的建议,伙计们!

标签: c++ while-loop printing text-processing


【解决方案1】:

问题是您正在逐字阅读。流使用“\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++的答案中得到想法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2012-05-01
    相关资源
    最近更新 更多