我正在从文本文件中删除一行,除了要删除的用户指定的一行外,每一行都复制到一个新的文本文件(temp.txt)中,然后删除原始文本文件( staffMembers.txt)并将temp.txt重命名为staffMembers.txt。C++如何从文本文件的末尾删除新行?
staffMembers.txt的内容如下:
1 | First Person | Manager | 123.45
2 | Second Person | Full Time | 123.45
3 | Third Person | Casual | 123.45
当staffMembers.txt的内容复制到TEMP.TXT其计算方法如下:
1 | First Person | Manager | 123.45
2 | Second Person | Full Time | 123.45
3 | Third Person | Casual | 123.45
*** new line ***
可能有人请解释一下我如何防止在文本文件末尾创建新行?我的代码如下:
void deleteStaffMember()
{
outStream.open("temp.txt", ios::app);
if(outStream.fail())
{
cout << "Unable to open temp.txt.\n";
exit(1);
}
inStream.open("staffMembers.txt");
if(inStream.fail())
{
cout << "Unable to open staffMembers.txt.\n";
exit(1);
}
else
{
cout << endl << "Please enter a staff members ID to delete: ";
cin >> deleteLine;
while(getline(inStream, line))
{
string firstCharacter;
firstCharacter += line[0];
if (firstCharacter != deleteLine)
{
outStream << line << endl;
}
else
{
inStream.close();
outStream.close();
cout << "Error. Unable to find staff member.\n" << endl;
break;
}
}
}
inStream.close();
outStream.close();
remove("staffMembers.txt");
rename("temp.txt", "staffMembers.txt");
cout << "The staff member has been deleted successfully.\n" << endl;
system("pause");
system("cls");
}
我不能删除ENDL从outStream < <线< < ENDL;因为那时TEMP.TXT的格式如下所示:
1 | First Person | Manager | 123.452 | Second Person | Full Time | 123.453 | Third Person | Casual | 123.45
第二个'for_each'可以是'copy(lines.begin(),lines.end(),ostream_iterator(outStream));'这对我来说似乎稍微更具描述性。或者你可以省略第一个'for_each',而不是'copy(lines.begin(),lines.end() - 1,ostream_iterator (outStream,“\ n”)); outStream << lines.back();'只是一个偏好问题。 –
2013-05-02 04:41:38
@JonPurdy你好,赶上。 – yngccc 2013-05-02 04:49:27