I have a little problem with my code. This should change every letter to some other i.e "a to g" etc. Everything is good but at the end the letters "u, v, w, x, y, z" are changed to "k, l, m, n, o, p" same as "a, b, c, d, e, f". I spent like 5 hours to find the problem and still don't know what to do.
#include <iostream>
#include <cstring>
int test(int a)
{
if(a==1){
return a;
}
return a - test(a-1);
}
char ciph(char *arr, int a)
{
int lenght = strlen(arr);
for(int i=0;i<lenght && arr[i]!='\0';i++)
{
if (isalpha(arr[i]))
{
if (arr[i]<=122 && arr[i]>=113)
{
arr[i]=arr[i]-test(a);
}
else
{
arr[i]=arr[i]+test(a);
}
}
}
std::cout << arr << std::endl;
}
int main()
{
int b=19;
char arr[100];
std::cin.getline(arr, 100);
std::cout << ciph(arr, b) << std::endl;
return 0;
}
This should change every letter to some other i.e "a to g" etc. Everything is good but at the end the letters "u, v, w, x, y, z" are changed to "k, l, m, n, o, p" same as "a, b, c, d, e, f".
Consider these lines of code
if (arr[i]<=122 && arr[i]>=113)
{ //^^^^^^^^^^^^^^^^^^^^^^^^^^^
arr[i]=arr[i]-test(a);
}
else
{
arr[i]=arr[i]+test(a);
}
You can rewrite those as (assumning an ASCII encoding):
if ( 'K' <= arr[i] && arr[i] <= 'R' )
{ // ^^^ ^^^
arr[i] -= test(a);
}
else
{
arr[i] += test(a);
}
Note that 'R'
is different from 'r'
. If your test case contains only lower case letters, the first branch will never be executed.
In general, you should avoid magic numbers like 122
and use a standard container like std::string
.