189k views
1 vote
Read first a user's given name followed by the user's age from standard input. Then use an ofstream object named outdata to write this information separated by a space into a file called outdata. Assume that this is the extent of the output that this program will do. Declare any variables that you need.

User Mylogon
by
6.2k points

1 Answer

3 votes

Answer:

/*

* Program to write data to text file.

*/

#include<iostream>

#include<fstream>

#include<string.h>

using namespace std;

int main()

{

//Variable to name and age of a person.

string name;

int age;

cout<<"Enter your name"<<endl;

cin>>name;

cout<<"Enter your age"<<endl;

cin>>age;

//Creating object of ofstream.

ofstream file;

file.open ("outdata.txt");

//Writing data to file named outdata.txt

file<<name<<" "<<age;

file.close();

}

Output:

Enter your name

John

Enter your age

25

Content of Output.txt:

John 25

Step-by-step explanation:

To write data to a file ofstream object is used. An ofstream object file is created first and then using this object a file named "outdata.txt" is created.

Finally using shift operator (<<), by means of operator overloading, name and age of person is transferred to file outdata.txt.

User Jesbus
by
6.0k points