In: Computer Science
Create a Visual Studio console project named exercise101. The main() function should prompt for the name of a text file located in the same directory as exercise101.cpp, and search for a word in the text file as follows:
Enter text file name:
Enter search word:
The program should print the number of occurrences of the word in the file:
occurrences of were found in If the file could not be opened then display:
File not found Use Stream file I/O as a guide to opening and reading a stream input file.
You should read the file word by word, where a word is a set of characters preceded and followed by white space including newlines.
Test you program by searching for the word "government" in the usdeclar.txt file available in Files / Source code / Exercise 10.1 Upload your exercise101.cpp source file to Canvas.
The Visual Studio C++ Program is given below. You are required to create a CPP project within your Visual Studio IDE and copy the below code and paste into the CPP source file of the project and save. Then put the text file (you want to be read by the program) in your projects folder where the cpp file exists within the Project directory. Then run the program and enter the name of the text file and word to be searched when prompted at the console.
#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
// declare the variables
string filename; // variable to store the filename from user
ifstream infile; // variable to store the file pointer
string search_word; // variable to store the word to be searched
string word; // variable to store the word read from file
int occurences = 0; // to store the count of search word
// inputting the input file name
cout << "Enter text file name: ";
getline(cin >> ws, filename);
cout << "Enter search word: ";
cin >> search_word;
// opening the file
infile.open(filename.c_str());
// check if file was opened or not
// if not then print error message and exit
if (!infile.is_open())
{
cout << "File not found!" << endl;
return -1;
}
// read each word from the file
while (infile >> word)
{
// compare each word to search word ignoring case
// if matches then increment the occurence value by 1
if ( _strcmpi(word.c_str(), search_word.c_str()) == 0)
occurences++;
}
infile.close();
// check if count is 0, if yes then print word not found
if (occurences == 0)
cout << "The word '" << search_word << "' was not found in the text file!" << endl;
else
// else print the frequency of the word found within the file
cout << "The word '" << search_word << "' was found " << occurences << " time(s) within the text file" << endl;
}
Input File
Console Output
NOTE: If you encounter any issue then kindly comment within the comments section and kindly give a thumbs up if you liked the answer.