C++ program to write and read values using variables in/from file

In this program, we will write and read variable's values in/from text file. Here you will learn how to write values in file and how to access them.

Write and read variable's values in the file

//C++ program to write and read values using variables in/from file.
#include <iostream>
#include <fstream>
 
using namespace std;
 
int main()
{
    char name[30];
    int age;
    fstream file;
 
    file.open("aaa.txt",ios::out);
    if(!file)
    {
      cout<<"Error in creating file.."<<endl;
      return 0;
    }
    cout<<"\nFile created successfully."<<endl;
 
    //read values from kb
    cout<<"Enter your name: ";
    cin.getline(name,30);
    cout<<"Enter age: ";
    cin>>age;
    //write into file
    file<<name<<" "<<age<<endl;
 
    file.close();
    cout<<"\nFile saved and closed succesfully."<<endl;
 
    //re open file in input mode and read data
    //open file
    file.open("aaa.txt",ios::in);
    if(!file){
        cout<<"Error in opening file..";
        return 0;
    }
    file>>name;
    file>>age;
 
    cout<<"Name: "<<name<<",Age:"<<age<<endl;
    return 0;
}

Output

    File created successfully.
    Enter your name: Mike
    Enter age: 21

    File saved and closed succesfully.
    Name: Mike,Age:21 





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.