In: Computer Science
1. create a .txt file and call it fruits.txt, add the following items to the file
Apple
Banana
Peach
Strawberry
Watermelon
Kiwi
Grape
_______
2. Write a program that does the following:
- Reads the fruit.txt
- Converts the contents into all uppercase
- Writes the uppercased values into a text file called "UpperFruit.txt"
OUTPUT SHOULD BE:
APPLE
BANANA
PEACH
STRAWBERRY
WATERMELON
KIWI
GRAPE
Hi,
Hope you are doing fine. I have coded the above question in C++ keeping all the conditions in mind. The explanation of the code has been clearly provided using comments that have been highlighted in bold. Note that I have also printed the output in console. You may avoid it as per your requirement.
Program:
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
//fruit is a string that stores each line of
the fruits.txt file
string fruit;
//upper is an array of string that stores the
entire contents of file.
string upper[100];
//count is used to count the number of lines
in fruits.txt
int count=0;
//opening fruits.txt in read
mode
ifstream myfile("fruits.txt");
//reading each line of file
while (getline (myfile, fruit)) {
//storing each line in each index of
upper
upper[count]=fruit;
//increasing count
count++;
}
//closing file
myfile.close();
//converting words in upper to
upercase
for(int i=0;i<count;i++)
{
//transform is used along
with toupper to convert a string to uppercase
transform(upper[i].begin(),
upper[i].end(), upper[i].begin(), ::toupper);
}
//opening file UpperFruit.txt in write
mode
ofstream myfile2("UpperFruit.txt");
//reading contents of upper
for(int i=0;i<count;i++)
{
//printing output to console
cout <<upper[i]<<"\n";
//writing contents to
UpperFruit.txt
myfile2 <<upper[i]<<"\n";
}
//closing file
myfile2.close();
}
fruits.txt
Executable code snippet:
Console output:
Output in file UpperFruit.txt: