2017-03-03 100 views
2

我有一個4行輸入文本文件,每行固定長度爲80個字符。我想用空格替換每個逗號。我編寫的代碼如下所示,並在Code :: Blocks IDE中編譯和運行。問題是輸出文件包含額外的行。請您幫助我糾正錯誤。我是C++的初學者。用C++替換文件中的字符

inputFile

outputFile

#include <iostream> 
#include <fstream> 
#include <string> 


using namespace std; 

int main() 
{ 
ifstream in("circArc.txt", ios::in | ios::binary); 


if(!in) 
{ 
    cout << "Cannot open file"; 
    return 1; 
} 

ofstream out("readInt.txt", ios::out | ios::binary); 
if(!out) 
{ 
    cout << "Cannot open file"; 
    return 1; 
} 

string str; 
char rep[80]; //replace array 

while(in) 
{ 
    getline(in,str); 
    for(int i=0; i<80; i++) 
    { 
     if(str[i] == ',') 
      rep[i] = ' '; 
     else 
      rep[i] = str[i]; 
     out.put(rep[i]); 
    } 
    out << endl; 

} 
in.close(); 
out.close(); 
return 0; 
} 

回答

1

使用中的問題

while(in) 
{ 
    getline(in,str); 

是您不檢查getline是否成功。無論如何,您正在繼續使用str

更換

while(in) 
{ 
    getline(in,str); 
    ... 
} 

while(getline(in,str)) 
{ 
    ... 
} 
+0

@Antony,看看這個SO問題的答案。 http://stackoverflow.com/questions/42571529/how-to-count-the-number-of-lines-in-a-file-using-c。看起來好像你遇到了同樣的情況。 –

+0

@Antony:因爲你正在調用getline()兩次 – androidFan

0

保持while()循環,但一旦前做/ while循環外面,然後在最後一行while循環中:

#include <iostream> 
#include <fstream> 
#include <string> 


using namespace std; 

int main() 
{ 
ifstream in("circArc.txt", ios::in | ios::binary); 


if(!in) 
{ 
    cout << "Cannot open file"; 
    return 1; 
} 

ofstream out("readInt.txt", ios::out | ios::binary); 
if(!out) 
{ 
    cout << "Cannot open file"; 
    return 1; 
} 

string str; 
char rep[80]; //replace array 

getline(in,str); 

while(in) 
{ 
    for(int i=0; i<80; i++) 
    { 
     if(str[i] == ',') 
      rep[i] = ' '; 
     else 
      rep[i] = str[i]; 
     out.put(rep[i]); 
    } 
    out << endl; 

    getline(in,str); 

} 

in.close(); 
out.close(); 
return 0; 
} 
+0

問題解決了這個問題也是。 – Antony

0

我覺得這裏的問題是你while循環的退出條件。您可以使用:

while(getline(in, str)) { 
    if (in.eof()) { 
     break; 
    } 
    /** This will get you out if you are reading past the end of file 
    * which seems to be the problem. 
    */ 
    ... 
0

的問題是,std::getline消除結束行的字符,如果它存在,所以你不能(容易)告訴我們,如果最後一個字符是一個最終的行或不行。

在我看來,你不需要wory有關數據此任務的格式,所以你可以只處理它一個字符時間:

ifstream in("circArc.txt", ios::in | ios::binary); 

ofstream out("readInt.txt", ios::out | ios::binary); 

for(char c; in.get(c); out.put(c)) 
    if(c == ',') 
     c = ' '; 

如果你真的要處理線那麼你需要檢查讀入的行是否包含行尾字符,並且只有在輸出中包含行結尾時纔會包含行尾:

ifstream in("circArc.txt", ios::in | ios::binary); 

ofstream out("readInt.txt", ios::out | ios::binary); 

for(std::string line, eol; std::getline(in, line); out << line << eol) 
{ 
    // only add an eol to output if there was an eol in the input 
    eol = in.eof() ? "":"\n"; 

    // replace ',' with ' ' 
    std::transform(std::begin(line), std::end(line), std::begin(line), 
     [](char c){ if(c == ',') return ' '; return c; }); 
}