2013-04-26 85 views
-1

我一直在想出一个代码,删除保存在文本文件中的数据,但无济于事。应该怎么做?在C++中,这是我的代码我该如何改进它,以便它删除保存的数据可能是条目的入口?如何删除保存在C++文本文件中的数据

#include<iostream> 
    #include<string> 
    #include<fstream> 
    #include<limits> 
    #include<conio.h> 
    using namespace std; 

    int main() 

    { 
    ofstream wysla; 
    wysla.open("wysla.txt", ios::app); 
int kaput; 

string s1,s2; 
cout<<"Please select from the List below"<<endl; 
cout<<"1.New entry"<<endl; 
    cout<<"2.View Previous Entries"<<endl; 
    cout<<"3.Delete an entry"<<endl; 
    cin>>kaput; 
    switch (kaput) 
{ 

case 1: 

    cout<<"Dear diary,"<<endl; 
cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    getline(cin,s1); 
    wysla<<s1; 
    wysla.close(); 

    break; 
    } 
    return 0; 
    } 
+0

这功课吗?数据是否为 – 2013-04-26 12:55:07

+1

?你是指文本文件中的任意行吗?你不能到位 – sherpya 2013-04-26 12:55:55

+3

只有一种方法可以从文件中间删除。将整个文件读入内存,删除内存中不需要的部分。从内存中写出整个文件。 – john 2013-04-26 12:58:24

回答

0

我可以给你我用于相同目的的最快方法。使用功能http://www.cplusplus.com/reference/cstdio/fseek去确切的位置。假设你在一个文件中保留名字。然后,名单将

Alex 
Timo 
Vina 

当你删除Alex,插入一个额外的字符的前缀,这样就可以将其标记为删除

-Alex 
Timo 
Vina 

必要时,您会不会表现出来。

如果你不想这样做,你必须复制没有特定的行。请参阅Replace a line in text file的帮助。在你的情况下,你用空字符串替换。

+0

你如何建议插入额外的字符? – 2013-04-26 13:57:38

0

在矢量的帮助下做到这一点。

//Load file to a vector: 
string line; 
vector<string> mytext; 
ifstream infile("wysla.txt"); 
if (infile.is_open()) 
{ 
    while (infile.good()) 
    { 
     getline (infile,line); 
     mytext.push_back(line); 
    } 
    infile.close(); 
} 
else exit(-1); 

//Manipulate the vector. E.g. erase the 6th element: 
mytext.erase(mytext.begin()+5); 

//Save the vector to the file again: 
ofstream myfile; 
myfile.open ("wysla.txt"); 
for (int i=0;i<mytext.size();i++) 
    myfile << mytext[i]; 
myfile.close(); 
相关问题