c++ - Unknown character at the end of string -


this practice problem hackerrank: https://www.hackerrank.com/challenges/caesar-cipher-1. output matches expected output of program there unknown character @ end of output string.can please tell me how unknown character occur @ end of string. here code :

#include <iostream> #include <string> #include<cstdio> using std::cin; using std::string; using std::cout; using std::endl;  int main() {     int k,n;     string text;     cin>>n;     cin>>text;     cin>>k;      (int = 0; <n; i++)     {          if(text[i] != '\0') //check if character null         {             if(isalpha(text[i])) //check if character alphabet             {                 int d=(int)text[i] ; //obtain ascii value                 int t=d+k;           //obtain encrypted value                 if(t>122)            //if encrypted value of character greater 122                 {                     int extra=t-122;                     int letter=97 +(extra-1);                     string ans= string()+char(letter);                     cout<<ans;                 }                  string ans= string()+char(t); //print encrypted character                 cout<<ans;              }              else              //if character not string, print             {                  cout<<text[i];              }         }     } } 

sample output: qmhhpi-syxd

my output: qmhhpi-syxd~

there few bugs in code:

  1. in if(t>122), checking if encrypted character ( caesar cypher) has value greater 122( ascii z). if value in range a-z , key added.
    thus, these 2 lines not correct.
    int extra=t-122; int letter=97 +(extra-1);
  2. your code incoherent. in if given length of string n, why using if(text[i] != '\0').
    also, why use
    string ans= string()+char(t); cout<<ans;.
    as pointed out @chris , these 2 lines cout << char(t);
  3. since k can vary between [0,100], it's better take mod 26. can check correct code here: ideone link

Comments