c++ - string arithmetic in cpp -


i wrote code ceasar cipher gave wrong answer in input. doubt after addition ascii value negative. please out.

int main() {      int n,k,i=0;     string s;     cin >> n;     cin >> s;     cin >> k;      if(n < 1 || n > 100 || k >100 || k < 0)         return 0;      if(k >= 26 )         k = k%26;      for(i=0;i<n;i++)     {         if(s[i] >= 65 && s[i] <= 90)         {             s[i] += k;             if(s[i] > 90)                 s[i] -= 26;         }         if(s[i] >= 97 && s[i] <= 122)         {             s[i] += k;             if(s[i] > 122 )                 s[i] -= 26;         }     }      cout << s;     return 0; } 

input:

   10    www.abc.xy    87 

expected output:

   fff.jkl.gh 

my output:

   .jkl. 

in part lowercase letters

if(s[i] >= 97 && s[i] <= 122) {    s[i] += k;    if(s[i] > 122 )       s[i] -= 26; }   

you have overflow problem (possibly). convert char first
between 0 , 26, , after applying caesar stuff, revert it:

if(s[i] >= 'a' && s[i] <= 'z') {    s[i] -= 'a';    s[i] += k;    s[i] %= 26;    s[i] += 'a'; }   

similar uppercase letters.

other that:
should use s.length() instead of letting user descide n is.
, happens if k negative?

btw., arithmetic , caesar.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -