In C++ Print the number of words that begin with a certain character. Let the us
ID: 3581239 • Letter: I
Question
In C++ Print the number of words that begin with a certain character. Let the user enter that character.
Example output:
dict txt Enter a character n Found 1271 words that begin with d n Test Case 8 To prevent hardcoding, this test case is hidden. To pass this case, be sure that all the programming requirements are met Test Case 9 Standard Input Files in the same directory dict txt Enter a character An Found 0 words that begin with @Mn Test Case 10 Files in the same directory Standard Input dict txt Enter a character An Found 0 words that begin with *MnExplanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open ("dict.txt"); // opening text file
string word;
int count = 0; // counts the number of words matching
char x ;
// taking user input
cout << "Enter a character : ";
cin >> x;
// as long as words are available in text
while ( file >> word )
{
//checking whether first word of word is same as input character
//first converting it to lowercase and comparing
if(tolower(word[0]) == tolower(x))
count++; // increasing the count if matched
}
// printing output
cout << "Found " << count << " words that begin with " << x << endl;
return 0;
}
/* Sampel Input : dict.txt
Chegg is a good platform to learn
Have some cup cakes.
Sample output
Test1:
Enter a character : g
Found 1 words that begin with g
Test2:
Enter a character : c
Found 3 words that begin with c
*/