Program does not work for no reason

Jun 20, 2015 at 4:40pm
Hey guys. I made program that tests if word is same when you read it normally and from right, like words : ana, ama, bmb,anavolimilovana, oko
When I run the program, it Always gives me back 1! When I type ana, ama etc. it is supposed to give me back 0, but It does not work properly for some reason.
My code:
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<fstream>
#include<utility>

using namespace std;

#define mp make_pair
#define pb push_back
#define xx first
#define yy second

const int INF = 1 << 29;
typedef long long lint;
typedef pair < int, int > tacka;


bool provjeri_palindrom (string tekst)
{
bool rez;
string naopako="";
int i;
for (i = tekst.size(); i>=0; i--)
{
naopako+= tekst[i];

}


if(naopako == tekst)
{
rez = 0;

}
else if(naopako!=tekst)
{
rez= 1;
cout << naopako << endl;
cout << tekst << endl;
}
return rez;
}

int main ()
{
string k;
cin >> k;
cout <<provjeri_palindrom(k) << endl;

return 0;
}
Jun 20, 2015 at 5:03pm
The problem is in your for loop.
When you iterate backwards through your string, you have to start from the string's length minus 1.
1
2
3
4
for (i = tekst.size()-1; i>=0; i--)
{
naopako+= tekst[i];
}


Because if your word is a 3 letter word, its length is 3.
However, the last letter of the word is at index 2.
So you need to set int i equal to tekst.size() - 1.
Because arrays start at index 0, so technically every letter is off by 1.

Apply this change and see if it works.

Hope that helps!
Last edited on Jun 20, 2015 at 5:14pm
Jun 20, 2015 at 5:04pm
for (i = tekst.size(); i>=0; i--)
HEre is the problem. tekst[tekst.size()] is going to be outside of the world and will be a null terminator. So your resulting string will start with null character, which s not what you want.
Jun 20, 2015 at 5:13pm
The first character that you copy, is tekst[tekst.size()]. That is one too many.
Topic archived. No new replies allowed.