Search code examples
c++file-handlingfile-copying

Copy only data needed from one big file to another


I'm making a project from my finals on cafe, in which I need user to select drinks from a made file drinks which has drinks in list like: 1. Coca-Cola $5 2. Pepsi $8 now I want user to press 1 if he or she wants to buy coca-cola and then the 1. coca-cola $5 copied to his file

I have tried all possible codes I could this is the closest code I could get

#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
main()
{
    ofstream outFile("userfile2.txt");
    string line;

    ifstream inFile("Drinks.txt");
    int count;
    cin>>count;
    while(getline(inFile, line))
    { 
       if(count>0 && count<2)
       {
         outFile << line <<endl;
       }
       count++;
     }

     outFile.close();
     inFile.close();
}

I expect that I can copy any drink the user wants from the drinks file to the user file has the user press 1 2 or 3 numbers from the list of drink shown to him at the time of code running.


Solution

  • it is very simple

    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    
    int main()
    {
      ofstream outFile("userfile2.txt");
      string line;
      ifstream inFile("Drinks.txt");
      int count;
      cin>>count;
      while(getline(inFile, line))
      { 
        if (--count == 0)
        {
            outFile << line <<endl;
            break;
        }
      }
    
      outFile.close(); // not mandatory, done automatically by the destructor
      inFile.close(); // not mandatory, done automatically by the destructor
    }