Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ program to write and read object using read an... >>
<< C++ program to write and read text in/from file...