Reputation:
I tried searching for a solution online but I could not find one. The closet I came is this A similar unanswered question on cplusplus.com
Here is my code....
int main()
{
char a[1000000],s[100000];
scanf("%s",s);
int i,l=strlen(s);
//cout<<l;
for(int i=0;i<l;i++)
a[i]=s[l-i-1]; //to reverse the word in s[]
cout<<a<<endl;
for(i=0;i<l;i++)
{
s[i]+=a[i]-96;
if(s[i]>'z')
{
int diff=s[i]-'z';
s[i]='a'+(diff-1);
}
}
cout<<s;
return 0;
}
//l=length of string.
//a[i]=is another string with word in s[] being reversed.
My problem is that when I execute this and give an input , say, world
it prints some weird characters.
I am unable to see any fault in the logic I applied and I feel frustrated now.
The question asked was that I am supposed to add two strings one of which is reversed version of the other one and that the addition is to be performed in such a way that 'a' + 'b' = 'c'
, 'd' + 'a' = 'e'
.... and 'z' + 'a' = 'a'
. So that the addition is closed under small-alphabets.
Upvotes: 0
Views: 400
Reputation: 1099
Your problem is that you're using a signed char (a signed byte). When the signed char goes over 127, then it flips negative. This causes your computation to miss the fact that the value is out of range, and when it's printed it's converted back to a high character.
You can simply replace your wrap around check with this:
while ((unsigned char)s[i] > 'z')
{
s[i] -= 26;
}
And then your program at least does what you wanted it to do. There are good suggestions in the comments for making it more robust as well.
Upvotes: 1