【发布时间】:2013-04-02 02:38:00
【问题描述】:
我正在编写一个程序来读取/写入包含员工信息的文本文件。 每个员工信息都存储在一个文本文件中,如下所示。 员工信息存储到四行。
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>
如何防止将换行符写入文件?
【问题讨论】:
-
您如何检查新行?文本文件通常在文件末尾有一个额外的
\n。但是,它通常被您的文本编辑器隐藏。新行是否显示在文本编辑器中?