我通过将每一行(用户指定的要删除的一行除外)复制到一个新的文本文件(temp.txt),然后删除原始文本文件(staffMembers.txt)来从文本文件中删除一行。 txt) 并将 temp.txt 重命名为 staffMembers.txt。
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");
}
我无法从outStream << line << endl;中删除endl ;因为 temp.txt 的格式如下:
1 | First Person | Manager | 123.452 | Second Person | Full Time | 123.453 | Third Person | Casual | 123.45