So I decided to check if the word is palindrome. So I made 2 string, and I have to input word(like "Hello"
).I don't understand how do I compare this 2 strings, and also I have an error with using word.length
with variable i
. How do I fix it? Is it necessary to change code or I can just change something in mine?
string word,s;
cin>>word;
for(int i=word.length()-1;i>=0;i--){
s[i]=word[i];
}
if(s==word)
cout<<1;
In fact there is no need to use an additional string to check whether a given string is a palindrome. You can perform such a check in a loop.
However using your approach you could write simpler. for example
if ( word == std::string( word.rbegin(), word.rend() ) ) std::cout << 1;
As for the error you are saying it seems that the compiler does not .like when you are comparing signed integer i with the unsigned integer value returned by the call word.length*().
Moreover as the string s is empty then you may not use the subscript operator
s[i]=word[i];
You could write either
s += word[i];
or
s.push_back( word[i] );
Preliminary you could reserve enough memory for the string s like
s.reserve( word.size() );