-1

テキストファイルに保存されたデータを削除するコードを考え出そうとしましたが、役に立ちませんでした。どのようにすればよいのでしょうか?? 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;
   }
4

2 に答える 2

0

私が同じ目的で使用した最速の方法を紹介できます。関数http://www.cplusplus.com/reference/cstdio/fseekを使用して、正確な場所に移動します。ファイルに名前を保持しているとします。次に、名前リストは次のようになります

Alex
Timo
Vina

を削除するときはAlex、追加の文字プレフィックスを挿入して、削除済みとしてマークできるようにします

-Alex
Timo
Vina

必要に応じて表示しません。

これをしたくない場合は、その特定の行を除いてコピーする必要があります。テキスト ファイルの行を置換する のヘルプを参照してください。あなたの場合、空の文字列に置き換えます。

于 2013-04-26T13:40:19.697 に答える
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();
于 2013-04-26T13:41:54.363 に答える