2014-02-16 65 views
0

无论哪里,在新行后面都有一个新行或(“\ n”)和一个空格(“”),我想忽略“\ n”只是在我的输出中打印空间,我怎么能这样做?如何忽略从C++中读取文本文件中的特定新行

这是一个例子:

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) 
     { 
      ?? 
     } 

回答

1

像这样做。该功能函数getline()将读取,直到\n字符

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

非常感谢。它工作正常。 – Omid

1

功能getline()(文档here)将读取并扔掉\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; 
} 
+0

非常感谢您的建议! – Omid

0

您可能希望这样:

#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测试可能是错误的。

+0

谢谢你的回答 – Omid

相关问题