In: Computer Science
C++
Read first a user's given name followed by the user's age from standard input. Then use an ofstream object named outdata (which you must declare) 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.
Code Segment:
#include<bits/stdc++.h>
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
// declaring variables to store data
string name;
int age;
// taking input from user
cin>>name>>age;
// declaring ofstream object
ofstream outdata;
// opening file named outdata.txt
outdata.open("outdata.txt");
// checking if the file is open
if(outdata.is_open())
{
// writing name followed by space and then age into the outdata.txt file
outdata<< name <<" "<<age;
// closing the file outdata.txt
outdata.close();
}
// if the file is not opened, display error opening in file
else
cout<<"error opening file";
}
Output:
Explanation:
As soon as you give the input Name and Age, a file named outdata.txt will be created in the same directory. And the given information will be written with a space between them in the outdata.txt file.