Write a C++ program that erase the nonalphabetical string from the vector.Ask us
ID: 3731781 • Letter: W
Question
Write a C++ program that erase the nonalphabetical string from the vector.Ask user to enter 3 string.
Example: string is: Apple,Cat,Ship,Bat,Car,Cry
Use push_back to add that in vector.
UserInput(How many char word want): 3
then delete Apple,Ship from the vector
Loop until user find correct word
UserInput(Guess a character from the word):r
Display:Word found: _ _ _
then delete the word of lenght 3 that has r in it
UserInput(Guess a character from the word):a
Display:Word found: _ a _
Now all the remaining word of lenght 3 has character a at same place
UserInput(Guess a character from the word):t
remove all the remaining word that has character t (cat, bat)
Display:Word found: _ a _
UserInput(Guess a character from the word):r
Display:Word found: _ a r
UserInput(Guess a character from the word):c
Display:Word found: c a r
Congratulations you win!!
Explanation / Answer
#include <iostream>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
//declaring vector of string type
vector <string> words;
//declaring 3 strings
string first, second, third;
//take input from user
cout<<" Enter 3 strings"<<endl;
getline(cin, first);
getline(cin, second);
getline(cin, third);
//push the strings in the vector
words.push_back(first);
words.push_back(second);
words.push_back(third);
int indexes[3];
//erase non alphabetical strings from the vector
// non alphabetical strings are those which contains letters other than alphabets
// traverse through each string in the vector
for(int i = 0; i < words.size() ; i++)
{
int flag = 0;
//traverse through each letter in individual string
for(char c : words[i])
{
if(!isalpha(c)){
//storing the indexes of strings to be deleted
indexes[i] = 1;
break;
}
}
}
//delete all the strings at stored indexes
for(int j = 0; j< 3; j++){
if(indexes[j] == 1){
auto index = std::find(begin(words), end(words), words[j]);
words.erase(index);
}
}
//display
cout<<" String after erasing";
for(int i=0; i<words.size() ; i++){
cout<<" "<<words[i];
}
return 0;
}
output
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.