0

So far I am able to open a txt file and store them as variables.

My txt file looks like this

Tim, 24, Male

I have been able to store them as variables such as name, age, gender

This is my code

ifstream inputfiles ("test.txt");
    if(!inputfiles.is_open())
    {

    }
    else
    {
        while(inputfiles >> name >> age >> gender)
        {
            cout << name << "\n";
            cout << age << "\n";
            cout << gender << "\n";
        }

However, my code doesn't store the values as variables when my txt file looks like this...

Tim
24
Male

How do I modify my code such that it can read my file line by line and store it in its variables?

user4167396
  • 29
  • 1
  • 7

1 Answers1

-1

If I am right, You want to store it like:

  1. Tim 24 Male
  2. John 25 Male

Use a class

    class data
    {
        public:
        char name[10],gen;
        int age;
        void getdata()
        {
            cout<<"Enter Name";
            gets(name);
            cout<<Enter age";
            cin>>age;
            cout<<"enter gender";
            cin>>gen;
        }
        void putdata()//use cout statements here
        {
        //put cout statements
        }
    };

Now in your main function,use write functon

fstream f;
f.open("YourFile.txt",ios::in|ios::out);    
data r;    
for(i=0;i<10;i++)
{
    r.getdata();
    f.write((char*)&r,sizeof(r));
}

Remember,always use read function to print the database values if you used write.

f.seekg(0,ios::beg);
while(!f.eof())
{
   f.read((char*)&r,sizeof(r));
}

If you want to store the text as it is without conversion...use put function.

Aditya Dev
  • 139
  • 1
  • 8