Take the code you wrote in part 1 and create a new function named interactiveStr
ID: 3842525 • Letter: T
Question
Take the code you wrote in part 1 and create a new function named interactiveStringCounter(). The function gives you three options: 'A' to add a string, 'C' to get a count of a specific string requested and 'X' to exit the program and return a dictionary of counts. I fan incorrect command is given a message should indicate this and ask for another command. If the name is not found when requesting a count ('C') then 0 should be displayed. See the interaction below for guidance. >>> interactiveStringCounter() Please enter a command 'A' for Add, 'C' for count, 'X' to exit:A Please enter a value: cat Please enter a command 'A' for Add, 'C' for count, 'X' to exit: cat Command not recognized please Please enter a command 'A' for Add, 'C' for count, 'X' to exit: cat Command not recognized please Please enter a command 'A' for Add, 'C' for count, 'X' to exit: cat Command not recognized please Please enter a command 'A' for Add, 'C' for count, 'X' to exit:A Please enter a value: cat Please enter a command 'A' for Add, 'C' for count, 'X' to exit:s Command not recognized please Please enter a command 'A' for Add, 'C' for count, 'X' to exit:C Please enter the name to get a count: cat z Please enter a command 'a' for Add, 'C' for count, 'X' to exit:A Please enter a value; mouse Please enter a command 'A' for Add, 'C' for count, 'X' to exit:X ('mouse' i 1, 'cat'; 2) >>>Explanation / Answer
#include <iostream>
#include <string>
#include <map>
using namespace std;
//Store the string entered in a map that maps strings to the count of string. Call this map 'dictionary'
map<string, int> dictionary;
void interaactiveStringCounter(){
char c;
//Make the user enter a command
cout<<"Please enter a command"<<endl<<"'A' for Add, 'C' for count, 'X' to exit:"<<endl;
cin>>c;
//Check if the command is A, C, X or none of these and act accordingly
//If 'A', then add a new string to the dictionary, or increase the count of the existing string
if(c == 'A')
{
cout<<"Please enter a value"<<endl;
string val;
cin>>val;
//If the string isn't in the map, add it or else increase its count
if(!dictionary[val])
//Adding new string
dictionary[val] = 1;
//Else, increasing count of previous string
else dictionary[val]++;
}
// Display the count
if(c== "C"){
cout<<"Please enter the name to get a count"<<endl;
string val;
cin>>val;
//Display the count of the string entered
cout<<dictionary[val]<<endl;
}
//Iterate and exit in case user enter 'X'
if(c=='X'){
//Iterate through the dictionary to display values
//exit from the program
return;
}
//Else the option entered is invalid
else {
cout<<"Command not recognized please try again."<<endl;
}
//Recursive function
interactiveStringCounter();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.