2014-02-16 63 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

相關問題