Reputation: 124
Their is a runtime error of 'out_of_range'. It works when i use i>0, but my first character does not get added to my string if i do so.
int main(){
string str;
string strR;
short count {0};
getline(cin,str);
int n=str.length();
for(size_t i=n-1;i>=0;i--)
strR.push_back(str.at(i));
if(str==strR)
cout<<"Yes\n";
else
cout<<"No\n";
return 0;
}
Upvotes: 0
Views: 88
Reputation: 23497
For i
of type size_t
, the condition i >= 0
is always true. After i
being zero, negative overflow occurs and i
becomes some large number. str.at(i)
then naturally throws.
Very simple correction:
for (size_t i = n; i > 0; i--)
strR.push_back(str.at(i - 1));
Alternatively, you can use a signed type for i
, such as int
. However, this may then broke for very large strings. I wouldn't use it in production code.
BTW, to check whether a string is a palindrome, you don't need to copy it. Simpler and faster would be just iterating over the half of the string and compare corresponding characters from the second half.
Upvotes: 3