我正在從文本文件中刪除一行,除了要刪除的用戶指定的一行外,每一行都複製到一個新的文本文件(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