In: Computer Science
Write a program in c++ to do the following:
2. Create an array to hold up to 20 integers.
3. Create a data file or download attached text file
(twenty_numbers.txt) that
contains UP TO 20 integers.
4. Request the input and output file names from the user. Open the
files
being sure to check the file state.
5. Request from the user HOW MANY numbers to read from the data
file,
up to twenty. Request the number until the user enters 20 or less,
but not less
than 0. The user enters the number of integers to read. The
integers are stored
in the file and are to be read from the file.
6. Write a function that reads from the opened data file: the
number
of integers the user wants to read, and store the numbers in
the array. For example, if the user wants to read 13 numbers,
read 13 of the 20 that may be in the file.
7. Write a function that writes to the opened output file AND
THE
CONSOLE, the numbers stored in the array.
8. NO GLOBAL variables are to be used. The input and output file
variables
must be passed into the functions as parameters, the number of
integers
to read and output must be passed in to each function, the array
must be passed
in to each function.
twenty_numbers.txt
12 15 68 19 49 28 40 46 39 40 1 18 22 22 50 99 100 2 30 19
C++ code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//function to print values
void print_numbers(int arr[],string str2,int x)
{
// open a file in write mode.
ofstream outfile;
outfile.open(str2.c_str());
for(int i=0;i<x;i++)
{
//console print
cout<<arr[i]<<" ";
//file print
outfile<<arr[i]<<" ";
}
}
//function to find numbers from file
void find_numbers(string str1,string str2,int x)
{
// open a file in read mode.
ifstream infile;
infile.open(str1.c_str());
//array to store elements
int arr[x];
int i=0;
while(i<x)
{
//read from file and store in array
infile>>arr[i];
i++;
}
//function call to print arrays in file 2
print_numbers(arr,str2,x);
}
//main function
int main()
{
//declaring string variables to store file names
char str1[100],str2[100];
//input strings
cout<<"Enter input and output file names";
cin>>str1>>str2;
//variable to store number of elements to read
int x;
cout<<"Enter how many numbers to read from data file: ";
cin>>x;
//function call
find_numbers(str1,str2,x);
return 0;
}
Sample run:
input file:
output file: