簡體   English   中英

如何防止在文件末尾寫入“ \\ n”

[英]How to prevent “\n” being written at the end of file

我正在編寫一個程序來讀取/寫入包含員工信息的文本文件。 每個員工信息都存儲在一個文本文件中,如下所示。 員工信息存儲在四行中。

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),並刪除包含員工信息的行。更新后的文件存儲在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>

如何防止換行符寫入文件?

至少有兩個選擇:

  • 您可以檢查寫入的行是否為最后一行,並在寫入之前修剪字符串。

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

從文件中提取文件時,請勿將eof()用作條件。 它不能很好地指示是否實際上還有任何要提取的內容。 更改為:

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

文本文件通常以一個\\n結尾,該\\n被文本文件隱藏。 如您所願,當您迭代時,將讀取最后一行,並提取最后的\\n 由於getline不在乎讀取\\n (畢竟是定界符),因此它看不到到達末尾,因此未設置EOF位。 這意味着即使沒有什么要讀取的內容,下一次迭代也會繼續, getline提取文件末尾的空白,然后將其寫入輸出。 這給了您這條額外的線。

或者,如果行變量僅包含“ \\ n”,則不要將“行”變量寫入“ outputempfile”

即這樣的事情:

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

不確定語法,但是這個想法應該可行

暫無
暫無

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

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