Using vectors to bleep some predefined strings - c++

So i'm currently doing the exercices in my programming book "Programming: Principles and practice using c++" from Bjarne Stroustrup and i'm curently stuck at one exercice. Basically, the exercice is to write a program that bleeps out words it doesn't like. The way it works is that the user inputs a string and the program repeats the word. If the word the user enters is part of the dislike vector, the word is replaced by "Bleep". (I don't know if I explained this right, but it shouldn't be to complicated to understand).
This is my version of the program:
int main()
{
string dislike = "Potato";
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
if(words==dislike)
{
cout << "Bleep!" << endl;
}
else
{
cout << words << endl;
}
}
system("pause");
return 0;
}
As you can see, this version isn't using vectors (and it should, because the exercice is right after the explanation of vectors in the chapter). So my question is, how can I implement a vector with many "dislike" words in it like this:
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
and make it so it works like my other version without vectors (repeats words, but bleeps the dislike words). I can't seem to understand how to navigate in a vector so that it only bleeps the "dislike" words.
If someone could give me a hand and explain to me how it works (please do not just give me the answer) it would be very appreciated.
Thank you for your time and help, learning c++ alone isn't always simple, and I thank this website for making my learning curve a bit easier.
bobicool

Ok, let me explain a simple approach to it. There are more elegant ones, but for now it's important that you get a feeling of how std::vector can be accessed and how to compose control structures correctly.
Step 1 - looping through all elements of a vector
You can use iterators to go through all elements of a vector.
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
// now *it gives access to the current element (here: current dislike word)
if (*it == words) {
// ... yeah, we found out the current word is on the list!
}
}
You get an iterator to the first element in a vector by calling begin(), then keep incrementing (++it) it until you reached the end of the vector. I use const_iterator here because I'm not going to modify any elements, if you need to, use iterator.
with a std::vector, indexing via [index] is also possible (but not recommended, usually):
for(size_t i = 0;i < dislike.size(); ++i) {
// dislike[i] is the current element
if (dislike[i] == words) {
// huuuuray! another BEEEP candidate
}
}
Step 2 - break the loop early
As soon as you know what for sure that we have a dislike word, you don't need to search the vector further.
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
break;
}
}
Step 3 - make a note if we handled a word already
bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
is_beep = true;
break;
}
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
cout << words << endl;
}
Step 4 - putting it all together
int main()
{
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
is_beep = true;
break;
}
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
cout << words << endl;
}
}
system("pause");
return 0;
}
Check out std::find for a more idiomatic solution - it basically saves you the inner loop. You can also get rid of that bool in the last code sample if you re-structure a bit. I'll leave that as an exercise to you (hint: keep the iterator alive and check out its value after terminating the loop).

int main()
{
vector<string> dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words;
cout << "Please enter some words: " << endl;
while(cin >> words)
{
if(find(dislike.begin(), dislike.end(), words) != dislike.end())
{
cout << "Bleep!" << endl;
}
else
{
cout << words << endl;
}
}
system("pause");
return 0;
}
For std::find add #include <algorithm> to your source.

use std::find(your_vector.begin(), your_vector.end(), words)
int main()
{
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
if(std::find(dislike.begin(), dislike.end(), words) != dislike.end())
{
cout << "Bleep!" << endl;
}
else
{
cout << words << endl;
}
}
system("pause");
return 0;
}

Here is my solution to that particular question in the book when i was reading it. :) hope it's self-explanatory.
/*THE QUESTION GOES LIKE;
Write a program that “bleeps” out words that you don’t like; that is, you read in words
using cin and print them again on cout. If a word is among a few you have defined, you
write out BLEEP instead of that word. Start with one “disliked word” such as string
disliked = “Broccoli”;
When that works, add a few more.*/
#include "std_lib_facilities.h" // this is a standard library header that came with
the book
int main () {
vector<string> dislike = {"Dislike", "Alike", "Hello", "Water"}; /* defining a vector
for the disliked words. */
vector<string> words; //initializing vector for the read words.
cout << "Please enter some words\n"; //prompt user to enter some words.
for( string word; cin >> word;) //this current word typed is read in.
words.push_back(word); // word read in are pushed into the vector "words".
sort(words); /* function for the standard library for sorting data...this makes the data from the vector "words" appears in alphabetical order. */
for (int i=0; i<words.size(); ++i){ /*this acts as an iterator. and goes through all the element of the vector "words". */
if(i==0 || words[i-1]!=words[i]){ /*this prevents the words from repeating....just an option incase the user enters same kinda words twice or more. */
if(words[i]!=dislike[0] && words[i]!=dislike[1] && words[i]!=dislike[2] && words[i]!=dislike[3]) /*This test checks whether the words typed match any of the elements of the vector "dislike".if they don't match; */
cout << words[i]<< '\n'; //prints out the words.
else
cout << "BlEEP!\n"; //if they match....print out "BlEEP!".
}
}
}

I am learning C++. This Program has been changed some.
Write a program that "bleeps" out bad words that you don't like; that is,
you read in words using cin and print them again on cout. If a word is among a few you have defined, you write out BLEEP and or have it to BLEEP(Sound) instead of that word. Start with one "bad word" such as -- string badword = "arse"; When that works, add a few more or write a whole program based on all the bad words that you do not want printed out.
while (cin >> words)
{
if(find(badwords.begin(), badwords.end(),words) !=badwords.end())
{
cout << " " << endl; // You can put Bleep in or leave it out (Blank) if blank
// it will leave a blank in the phrase when it prints
Beep(523,500); // This is to Bleep (Sound) when a bad word is found
cin.get();
}
else
{
cout << words << endl;
}
}
Since someone gave the answer I have Changed the program some. That is for you to learn.
This runs on Visual Studio Express 2012

I have solved this problem using the ideas that have already been learned in the previous chapters, not going beyond what you understand.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> disliked;
//adding disliked words to the vector
disliked.push_back("dog");
disliked.push_back("cat");
disliked.push_back("goat");
disliked.push_back("cow");
disliked.push_back("sheep");
disliked.push_back("pig");
string words=""; //this variable will store the input from the user.
while(cin>>words)
{//test every entered word to see if it's equal to any word listed in disliked words.
if(words==disliked[0] ||//or
words==disliked[1] ||//or
words==disliked[2] ||//or
words==disliked[3] ||//or
words==disliked[4] ||//or
words==disliked[5]){
cout<<"Bleeps";}
else{
cout<<words;}
}
return 0;
//Not that I have not gone beyond what has been covered in the previous chapters.
//I know their are beautiful solutions to this problem.
//Keep learning you will know everything.
}

This question was asked a long, long time ago so the author is probably professional at this point lol, but here is simpler yet working solution for anybody who is looking for the same answer. I am learning from the beginning through Bjarne book so im not yet "affected" with higher knowledge to confuse you with but with solutions that are good enough to work based on how far we are in the book. :)
// program that bleeps out words we dont like
vector <string> words;
vector <string> bwords = {"this", "that", "then"}; //bleeped words
string sword; // temporary word
cout << "Enter few words: ";
for (string tword; cin >> tword;) // read in words
words.push_back(tword);
//check if they match beeped words
cout << "\n\nWords:\n";
for (int i = 0; i < words.size(); i++) //take word[i] from the vector
{
sword = words[i]; // temporary variable is now word[i]
for (int j = 0; j < bwords.size(); j++) // take beeped word[j] from saved words
{
if (words[i] == bwords[j]) // is word[i] same as bleeped word[j]
sword = "BLEEP"; // if word[i] is same then replace sword with BEEP
}
cout << sword << "\n"; // now we checked first word and if it matches with any of the bleeped words then it will cout bleep, otherwise it will cout first word.
}
Now in this example you can add many new bleeped words and you wont need to change the code.
This is not the best solution in "real life" programming, but at this point in the book we learned for, if, vector(not a lot of it), cout, cin.. etc so anything else just looks confusing..until this point we dont know yet about using :: , begin, true/fals, cin.get or anything like that.

//Josef.L
//2019/7/11
int main(void){
vector <string> inpute;
for(string pat; cin >>pat;){
inpute.push_back(pat);
}
for(int i=0; i < inpute.size(); i++){
if("work"== inpute[i]){
cout<<"bleep! "<<endl;}
else if("life" == inpute[i]){
cout<<"bleep! "<<endl;
}
else if("broccoli" == inpute[i]){
cout<<"bleep! "<<endl;
}
else if("homework" == inpute[i]){
cout<<"bleep! "<<endl;
}
else{
cout <<inpute[i]<<endl;
}
}
return 0;}
//However, the entire source code is too long and boring, so there should be an improvement.

That's my solution, where you can add as many words as you want without changing the code.
#include "std_lib_facilities.h"
int main()
{
vector<string> dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
vector<string> words;
for (string temp_word; cin >> temp_word; )
{
for (int i = 0; i < dislike.size(); ++i)
{
if (temp_word == dislike[i])
{
words.push_back("BLEEP");
break;
}
else if (i == dislike.size() - 1 && temp_word != dislike[dislike.size() - 1])
{
words.push_back(temp_word);
break;
}
}
}
for (string temp_word : words)
{
cout << temp_word << ' ';
}
keep_window_open();
}

“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” ― Steve Jobs
#include "std_lib_facilities.h"
int main()
{
vector<string>disliked;
disliked.push_back("Apple");
disliked.push_back("OliveOil");
disliked.push_back("Strawberry");
disliked.push_back("Lemon");
cout<<"Please type some words:"<<"\n";
string words=" ";
while(cin>>words)
{
if (words==disliked[0] | words==disliked[1]|
words==disliked[2] | words==disliked[3])
{cout<<"BLEEP"<<"\n";}
else{cout<<words<<"\n";}
}
keep_window_open();
}

Related

(1) Why does it not recognize this is a palindrome & (2) how do I have it print the original input WITH the spaces?

I've searched all over to try to answer my own questions, but I'm hitting a wall here. I've been working on this same exercise for three days and getting frustrated, hence my very first post! This is a school assignment, but I really want to understand why this isn't working. When I use input "bob" it returns "bob is a palindrome" as expected. When I input "bobby" it returns "bobby is not a palindrome" as expected. All good there. It took me forever to figure out how to remove spaces from my input when using the sentence "never odd or even" but I managed to do that successfully, too. But here's the rub: (1) even after the spaces are removed, it seems to think that "neveroddoreven" is NOT a palindrome - why? What am I missing? Additionally, and this is probably a stupid question (but this is my first foray into programming and I'm a total newbie), how do I get it to output the original userInput before I removed the spaces in the final output? Currently the below code outputs "neveroddoreven is not a palindrome". Thanks in advance for any pointers you can give me.
#include <string>
#include <cctype>
using namespace std;
int main() {
string userInput;
int startInput;
bool isPalindrome = true;
getline (cin, userInput);
startInput = userInput.length();
for(int i = 0; i<userInput.length(); i++)
if(userInput[i] == ' ') userInput.erase(i,1);
for (int i = 0; i<(startInput / 2); i++){
if (userInput[i] != userInput[(startInput -1 ) -i])
isPalindrome = false;
}
if (isPalindrome){
cout << userInput << " is a palindrome" << endl;
}
else {
cout << userInput << " is not a palindrome" << endl;
}
return 0;
}
After you erase all the spaces, startInput no longer refers to the actual length of the string. That means this comparison:
if (userInput[i] != userInput[(startInput -1 ) -i])
is not comparing the correct characters.
You can fix this by adding this line:
startInput = userInput.length();
after doing the erasing.
Here's a demo.
Also, in your erase code, this comparison i<userInput.length() is not a good idea, since you are comparing a signed and unsigned value. Also, you don't erase adjacent spaces. A simpler way to do that would be:
userInput.erase(std::remove(std::begin(userInput), std::end(userInput), ' '),
std::end(userInput));
As others have pointed out, the problem is that startInput doesn't take into account that you erase some spaces. So move the the line startInput = userInput.length(); so that it is just after the erase-loop.
An alternative solution that will not change the original input could be:
#include <iostream>
#include <string>
int main()
{
std::string userInput;
std::string userInputNoSpace; // Use one more string
int startInput;
bool isPalindrome = true;
std::getline(std::cin, userInput);
// Copy all characters that are NOT space to the new string
for (auto c : userInput)
{
if (c != ' ')
{
userInputNoSpace += c;
}
}
startInput = userInputNoSpace.length();
for (int i = 0; i<(startInput / 2); i++)
{
if (userInputNoSpace[i] != userInputNoSpace[(startInput -1 ) -i])
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
{
std::cout << userInput << " is a palindrome" << std::endl;
}
else
{
std::cout << userInput << " is not a palindrome" << std::endl;
}
return 0;
}
Input:
never odd or even
Output:
never odd or even is a palindrome

How to count number of words in a string?

I have prompted the user to input a string in the main function in my program and store it userString, and want to display how many words there are.
This is the function I intend to call from main:
int countWords(string d) {
string words = " ";
for (int e = 0; e < d.length(); e++) {
if (isspace(d[e])) {
cout << "The string " << words << "word(s). ";
}
}
return words;
}
I read somewhere that the function should actually count the number of white spaces (which is why I used isspace()), and not the words themselves.
How do I go about counting the number of words there are in the string and displaying it in the same function? I am having trouble figuring it out and I'm getting errors.
I also cannot use library functions.
Expected output:
The string "2020" has one word.
The string "Hello guys" has two words.
If you don't want to use boost, a simple for loop will do.
#include <cctype>
...
for(int i = 0; i < toParse.length(); i++){
if (isblank(toParse[i])){
//start new word
}
else if (toParse[i] == '.'){
//start new sentence
}
else if (isalphanum(toParse[i])){
//add to your current word
}
}
edit: you can just increment an integer where you see the //start new word.
try boost::split(), which will put words into a vector
Also, if you want to count something in a range satisfying some condition, you can think in std::count_if
Example:
int countWords(std::string d)
{
int w = std::count_if(d.begin(), d.end(), [](char ch) { return isspace(ch); });
std::cout << "The string \"" << d << "\" has " << w + 1 << " words." << '\n';
return w;
}

How do i take the initials of all the parts of one's name except the last name?

Hi i am trying to write a c++ program where the user will enter a name lets say for example: Tahmid Alam Khan Rifat and the computer will print the formatted version of the name which in this case will be: Mr. T. A. K. Rifat. I have included the code below. You will be able to see that I got close but still not exactly what i wanted. Please help.
#include<iostream>
#include<string>
using namespace std;
class myclass{
private:
string name,temp;
string p;
int i,j,sp;
public:
void work(){
cout << "Enter the name of the male student: ";
getline(cin,name);
cout << endl;
cout << "The original name is: ";
cout << name;
cout << endl << endl;
cout << "The formatted name is: " << "Mr." << name[0] << ".";
for(i=0;i<name.size();i++){
if(name[i]==' '){
sp=i;
for(j=sp+1;j<=sp+1;j++){
temp=name[j];
cout << temp << ".";
}
}
}
for(i=sp+2;i<name.size();i++){
cout << name[i];
}
cout << endl;
}
};
int main(){
myclass c;
c.work();
}
I guess the easiest way to solve this is to tokenize your string, print the first character from it, except from the last, where you print its full size.
To tokenize, you can do something like that:
std::vector<std::string> tokenize(std::istringstream &str)
{
std::vector<std::string> tokens;
while ( !str.eof() ) {
std::string tmp;
str >> tmp;
tokens.push_back(tmp);
}
return tokens;
}
Now you can easily transverse the tokens:
int main()
{
std::string name;
cout << "Enter the name of the male student: ";
getline(cin,name);
cout << endl;
cout << "The original name is: ";
cout << name;
cout << endl << endl;
std::istringstream str(name);
std::vector<std::string> tokens = tokenize(str);
for ( int i = 0 ; i < tokens.size() - 1; ++i)
std::cout << tokens[i][0] << ". ";
cout << tokens[tokens.size() - 1] << endl;
}
I hope this helps :)
It is probably a simpler version (originally I wrote this in C, you could easily convert it to C++ though, since the logic remains the same).
I have accepted the name and then inserted a space at the beginning of the string and one more space at the end, before the NULL character ('\0')
The program checks for a space.
When it encounters one, it checks for the next space that occurs in the string.
Now occurrence of this space helps us to identify an important determining factor as to what the next action should be.
See, if there is an null character after this subsequent space, then we can conclude that the subsequent space was the one we inserted at the end of the string.
That is, the space which occurs after the primary space, which came before the surname. Bingo!
You get the precise index of the array, from where the surname starts! :D
Looks long, but really is simple. Good luck!
#include<stdio.h>
#include<string.h>
void main()
{
char str[100]; /*you could also allocate dynamically as per your convenience*/
int i,j,k;
printf("Enter the full name: ");
gets(str);
int l=strlen(str);
for(i=l;i>=0;i--)
{
str[i+1]=str[i]; //shifting elements to make room for the space
}
str[0]=' '; //inserting space in the beginning
str[l+1]=' '; str[l+2]='\0'; //inserting space at the end
printf("The abbreviated form is:\n");
for(i=0;i<l+1;i++) //main loop for checking
{
if(str[i]==' ') //first space checker
{
for(j=i+1; str[j]!=' ';j++) //running loop till subsequent space
{
}
if(str[j+1]!='\0') //not the space after surname
{
printf("%c.",str[i+1]); //prints just the initial
}
else
for(k=i+1;str[k]!='\0';k++) //space after surname
{
printf("%c", str[k]); //prints the entire surname
}
}
}
}
Change your loop to the following:-
for(i=0;i<name.size();i++)
{
if(name[i]==' ')
{
initial = i + 1; //initial is of type int.
temp = name[initial]; //temp is char.
cout << temp << ".";
}
}
Try ravi's answer to make your code work, but I wanted to point out that there are more intuitive ways to program this which would make maintenance and collaboration easier in the future (always a good practice).
You can use an explode() implementation (or C's strtok()) to split the name string into pieces. Then just use the first character of each piece, disregarding the last name.
I think your question has already been answered. But in the future you could consider splitting up your program into more simple tasks, which makes things easier to read. Coupled with descriptive variable and function names, it can make a program easier to comprehend, and therefore to modify or fix later on.
Disclaimer - I am a beginner amateur programmer and this is just for ideas:
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
// I got this function from StackOverflow somewhere, splits a string into
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
std::istringstream is(line);
return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names {
private:
std::vector<std::string> full_name_;
void TakeInput() {
std::cout << "Enter the name of the male student: " << std::endl;
std::string input;
getline(std::cin,input);
full_name_ = LineSplit<std::string>(input);
}
void DisplayInitialsOfFirstNames() const {
std::cout << "Mr. ";
for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
std::cout << full_name_[i][0] << ". ";
}
};
void DisplayLastName() const {
std::cout << full_name_.back() << std::endl;
}
public:
void work() {
TakeInput();
DisplayInitialsOfFirstNames();
DisplayLastName();
};
};
int main(){
Names n;
n.work();
}

Searching substrings

I am a programming student. I have been asked to write a program that searches for a substring of another string, but I am not suppose to use the find() function that is provided in the string class. The code I have written thus far works, but it uses the find() function. How can I change this to not use the find function and still give me the location of the substring? Here is my code:
#include <iostream>
#include <string>
using namespace std;
int f_r(string, string);
int main()
{
string s;
string t;
cout << "\nEnter the string to be searched: ";
getline(cin,s);
cout << "Now enter the string you want to search for: ";
cin >> t;
if (f_r(s,t) == 0)
{
cout << "\n Substring could not be found.";
}
else
{
cout << "\nThe index of substring is = " << f_r(s,t) << endl;
}
system("PAUSE");
return 0;
}
int f_r(string str, string c)
{
int pos = 0;
pos = str.find(c, pos);
if (pos > str.length())
{
return 0;
}
else
{
pos++;
return pos - 1;
}
}
You need to search for matches within the string ONE character at a time, i.e. seeing the strings as if they were arrays of characters (since you're apparently working in C/C++ that is quite convenient since string and char[] are synonymous).
You will likely need to maintain indexes or pointers into the current location in both strings..
This will be the naive / initial approach, and when you get that working rather well, assuming you are a bit curious, you'll start wondering if there are more efficient ways of doing so, for example by skipping some characters in some cases, or by using general statistics about text in the underlying languages.
This art may help:
|_|_|_|_|_|_|_|_|_|_|_|
^ ^
i i+j
|
|_|_|_|_|
^
j
int search(char *a,char *b)
{
int i=0,j=0,k=0,m,n,pos;
m=strlen(a);
n=strlen(b);
while(1)
{
while((a[i]==b[j]) && b[j]!=0)
{
i++;
j++;
}
if (j==n)
{
pos=i-j;
return(pos);
}
else
{
i=i-j+1;
j=0;
}
}}
I have this code with me. I hope it will help you.
Note:- its an old code

Palindrome program isn't comparing properly

I'm currently learning about vectors and trying to make a palindrome program using them. This is a simple program and so far, I'm trying to make it identify "I am what am I." as a palindrome properly. This is my program so far:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector <string> sentVec;
void getSent(string sent);
void readBackwards(string sent);
int main()
{
string sent;
getSent(sent);
readBackwards(sent);
return 0;
}
void getSent(string sent)
{
cout << "Enter your sentence:" << endl;
getline (cin,sent);
string currentWord, currentLetter;
for (int i = 0; i < sent.length(); i++)
{
currentLetter = sent[i];
if (currentLetter == " ") // inserts word
{
currentWord += sent[i];
sentVec.push_back(currentWord);
currentWord = "";
}
else if (currentLetter == ".") // inserts period
{
sentVec.push_back(currentWord);
currentWord = sent[i];
sentVec.push_back(currentWord);
}
else
{
currentWord += sent[i];
}
}
}
void readBackwards(string sent)
{
string sentForwards, sentBackwards;
// create sentence forwards and backwards without the period.
for (int i = 0; i < sentVec.size() - 1; i++)
{
sentForwards += sentVec[i];
}
for (int j = sentVec.size() - 2; j >= 0; j--)
{
sentBackwards += sentVec[j];
if (j == sentVec.size() - 2)
{
sentBackwards += " ";
}
}
cout << "Sentence forwards is: " << sentForwards << endl;
cout << "Sentence backwards is: " << sentBackwards << endl;
if (sentForwards == sentBackwards)
{
cout << "This sentence reads the same backwards as forwards." << endl;
}
else
{
cout << "This sentence does not read the same backwards as forwards." << endl;
}
}
When I run this program, it prints:
Enter your sentence:
I am what am I.
Sentence forwards is: I am what am I
Sentence backwards is: I am what am I
This sentence does not read the same backwards as forwards.
Why does this not trigger the if loop when comparing the two sentences?
Because sentBackwards isn't the same as sentForwards, because sentBackwards has a trailing whitespace at the end, and thus they aren't the same.
I am unsure how your program detects palindromes, but here is a simple iterative method:
#include <string>
bool isPalindrome(std::string in) {
for (int i = 0; i < in.size() / 2; i++) {
if (in[i] != in[in.size() - 1 - i]) {
return false;
}
}
return true;
}
It returns true if the string passed as an argument is a palindrome
You should not only learn about vector, but also the STL algorithm functions such as std::reverse.
As the other answer given pointed out, one vector has a trailing whitespace. You could have avoided all of that by simply taking the original vector, copying it to another vector, and calling std::reverse. There is no need to write a loop:
void readBackwards()
{
// copy the vector
std::vector<std::string> sentBackwards = sentVec;
// reverse it
std::reverse(sentBackwards.begin(), sentBackwards.end());
// see if they're equal
if (sentVec == sentBackwards)
cout << "This sentence reads the same backwards as forwards." << endl;
else
cout << "This sentence does not read the same backwards as forwards." << endl;
}
This works, since std::vector has an overloaded operator == that compares the items in each of the two vectors and returns true if all items are the same.
In addition to this, reading into a vector can be accomplished much more easily than what you attempted.
#include <sstream>
#include <algorithm>
//...
void getSent(string sent)
{
// remove the periods(s)
auto iter = std::remove_if(sent.begin(), sent.end(), [] (char ch) { return ch == '.';});
sent.erase(iter, sent.end());
// copy the data to a vector
std::istringstream iss(sent);
string currentword;
while ( iss >> currentword)
sentVec.push_back(currentword);
}
Note that we use the std::istringstream to serve as the space delimited parser, alleviating the need to write a loop looking for the space. Also, the std::remove_if algorithm is used to remove any period characters from the string before we start to store the individual strings into a vector.
So basically, the only loop in this whole setup is the while to read from the stream into the vector. Everything else is accomplished by using the algorithm functions, and taking advantage of the various member functions of std::vector (like the overloaded ==)