簡體   English   中英

如何通過c ++忽略從文本文件中讀取的特定新行

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

無論何時,新行后面都有一個新行或(“\\ n”)和一個空格(“”),我想忽略“\\ n”並只打印輸出中的空格,我該怎么辦?這個?

這是一個例子:

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字符,因此不需要在字符串中搜索它。

做這樣的事情:

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;
}

像這樣做。 函數getline()將讀取直到\\n字符

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

你可能想要這個:

#include <cctype>
#include <iostream>
#include <sstream>

int main() {
    std::istringstream input(""
        "newegg\n"
        " bizrate\n"
        "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的測試可能是錯誤的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM