如何通过 C++ 在读取文本文件时忽略特定的新行

how to disregard specific new lines in reading from a text file by c++

本文关键字:新行 文件 C++ 何通过 读取 取文本      更新时间:2023-10-16

无论在哪里,新行之后都有一个新行或("")和一个空格("),我想忽略"",只打印输出中的空格,我该怎么做?

这是一个示例:

newegg
 bizrate

想要将其更改为:

newegg bizrate

我很困惑,因为我想我不能通过逐行阅读来做到这一点! 下面是我的粗略代码,我不知道如何继续...提前非常感谢。

ifstream file ("input.txt");
ofstream output("output.txt");
string line;
if(file.is_open())
{
    while (!file.eof())
    {
        getline (file, line);
        if (line.find("n"+' ') != string::npos)
        {
            ??
        }

这样做。函数 getline() 将读取到n字符

getline(file, line);
cout<<line;
while (!file.eof())
{        
   getline(file, line);
   if (line[0]==' ')
   {
        cout <<" "<<line;
   }
   else
   {
         cout <<"n"<<line;
   }
}

函数getline()(此处的文档)将读取并丢弃n字符,因此无需在字符串中搜索它。

只需执行以下操作:

bool first = true;
while (!file.eof())
{
    getline(file, line);
    // you may want to check that you haven't read the EOF here
    if (!first)
    {
        cout << " ";
    }
    else
    {
        first = false;
    }
    cout << line;
}

你可能想要这个:

#include <cctype>
#include <iostream>
#include <sstream>
int main() {
    std::istringstream input(""
        "neweggn"
        " bizraten"
        "End");
    std::string line;
    while(std::getline(input, line)) {
        while(std::isspace(input.peek())) {
            std::string next_line;
            std::getline(input, next_line);
            line += next_line;
        }
        std::cout << line << 'n';
    }
}

请注意:EOF的测试可能是错误的。