2013-04-10 82 views
0

我正在編寫一個程序來讀取/寫入包含員工信息的文本文件。 每個員工信息存儲在如下文本文件中。 員工信息存儲到四行。如何防止在文件末尾寫入「 n」

W00051 M 
Christopher Tan 
1200.00 150.00 1400.20 156.00 200.00 880.00 1500.00 8000.00 800.00 120.00 1600.00 1800.00 
1280.00 1500.00 140.80 1523.00 2000.00 2300.00 2600.00 8800.00 19800.00 1221.00 3000.00 1900.00 
W00012 E 
Janet Lee 
2570.00 2700.00 3000.00 3400.00 4000.00 13000.00 200.00 450.00 1200.00 8000.00 4500.00 9000.00 
1238.00 560.00 6700.00 1200.00 450.00 789.00 67.90 999.00 3456.00 234.00 900.00 2380.00 

我有接受員工的ID(W00012),並刪除其中包含員工information.The更新的文件存儲中tempfilesource行刪除僱員職能。

void delete_employee(char filesource[],char tempfilesource[],int employee_line,char inputid[]) 
{ 

char charline[255]; 
string line; 
int linecount = 1; 

ifstream inputempfile; 
ofstream outputempfile; 
inputempfile.open(filesource); 
outputempfile.open(tempfilesource); 

outputempfile.precision(2); 
outputempfile.setf(ios::fixed); 
outputempfile.setf(ios::showpoint); 

if (inputempfile.is_open()) 
{ 

while (getline(inputempfile,line)) 
{ 


    if((linecount<employee_line || linecount>employee_line+3)) 
    { 
    outputempfile<< line; 
    } 
    linecount++; 
} 
inputempfile.close(); 
outputempfile.close(); 
} 

}

的問題時,我想刪除的員工位於文本文件的底部出現。 和更新的文件包含一個空白換行符:

W00051 M 
Christopher Tan 
1200.00 150.00 1400.20 156.00 200.00 880.00 1500.00 8000.00 800.00 120.00 1600.00 1800.00 
1280.00 1500.00 140.80 1523.00 2000.00 2300.00 2600.00 8800.00 19800.00 1221.00 3000.00 1900.00 
<blank newline> 

我怎樣才能防止被寫入文件中的新行?

+0

你是如何檢查新行?文本文件通常在文件末尾有一個額外的'\ n'。但是,它通常被您的文本編輯器隱藏。新的一行是否顯示在文本編輯器中? – 2013-04-10 10:05:54

回答

0

至少有兩個選項:

  • 您可以檢查寫行是否是最後一行,寫之前裁剪的字符串。

  • 完成寫入後,可以從文件中刪除最後一個字符。

+0

是的,換行符顯示在我的文本編輯器中,我使用的是崇高的文本。 原始文本文件沒有空白的新行。 – soulchild 2013-04-10 10:08:45

+0

我檢查了字符串,奇怪的是裏面沒有「\ n」.. – soulchild 2013-04-10 10:13:12

0

從文件中提取時不要使用eof()作爲條件。它並沒有很好地說明是否有任何剩餘的東西需要提取。將其更改爲:

while (getline(inputempfile,line)) 
{ 
    if((linecount<employee_line || linecount>employee_line+3)) 
    { 
    outputempfile<< line; 
    } 
    linecount++; 
} 

文本文件通常有一個額外的\n這是由文本文件中的隱藏結束。就像你所做的那樣,當你迭代時,最後一行將被讀取,並且最終的\n將被提取。由於getline不關心超出\n(即所有分隔符),因此它看不到它已到達末尾,因此EOF位未設置。這意味着即使沒有剩下可讀的內容,下一次迭代也會繼續,getline會提取文件末尾處的空白,然後將其寫入輸出。這給你這個額外的線。

+0

感謝您的提醒。我改變了它,還有新的空白換行符。 – soulchild 2013-04-10 10:12:38

+0

@soulchild嗯......你怎麼確定有一個空行?在文本編輯器中?其實,我不明白。你不應該得到任何換行符。你沒有做'<< endl'。你確定這是你的真實代碼嗎? – 2013-04-10 10:13:20

+0

我的文本編輯器在左側顯示行數。刪除位於底部的員工後,顯示了4行數據,但我的文本編輯器顯示行數爲'5'。 是的,這是我的真實代碼。 – soulchild 2013-04-10 10:19:29

0

或者ü不寫「行」變量「outputempfile」如果行變量只包含「\ n」個

即是這樣的:

while (getline(inputempfile,line)) 
{ 
    if((linecount<employee_line || linecount>employee_line+3) && strcmp(line,"\n")==0) 
    { 
    outputempfile<< line; 
    } 
    linecount++; 
} 

不知道的語法,但這個想法應該工作