(PLEASE USE C++)
(PLEASE USE THE EXAMPLE GIVEN)
Question 1: [10 pointes] the input file inFile.txt stores a number of words with possible replication. Each word is stored on a separate line. The number of words within inFile.txt is stored as the first line in that file.
Write and test a program that reads the words from inFile.txt and prints them in outFile.txt without replication as well as the number of replication for each word.
Hint: to implement the above program, one must use a table of pointers to C-Strings as well as an array of counters; each counter keeps track of the count of a given word among all words within the input file.
Input File (inFile.txt)
5
smith
sara
john
john
smith
Output File (outFile.txt)
smith 2
john 2
sara 1
Question 2 [10 pointes] repeat Question 1 using an array of object strings as well as an array of counters and file IO.
C++ CODE:
#include <bits/stdc++.h>
#include <string>
#include <fstream> //for dat file handling
using namespace std;
int main()
{
fstream file1("input.txt"); // reading input from file
string str;
int str_len = 0;
bool check_string_found = 0;
string *arr;
int *counters;
int size;
file1 >> size;
arr = new string[size];
counters = new int[size];
while (file1 >> str)
{
if(str.length()!=0)
{
check_string_found = 0; // bool type variable to store whether the string is equal or not
for (int i = 0;i < str_len;i++)
{
if (str == arr[i]) //checking both strings are same or not
{
check_string_found = 1;
counters[i]++;
}
}
if (!check_string_found) // checking string is found or not
{
counters[str_len] = 1;
arr[str_len++] = str;
}
}
}
fstream file12("output.txt"); // writing output into file
for (int i = 0;i < str_len;i++) //printing frequency of each string
{
file12 << arr[i] << ": " << counters[i] << endl;
}
file1.close(); //closing file
file12.close(); //closing file
delete[] arr; //dealloacting memory
delete[] counters; //dealloacting memory
return 0;
}
Input:
Output:
If you have any doubt feel free to ask and if you like the answer please upvote it .
Thanks
Get Answers For Free
Most questions answered within 1 hours.