This is a practice problem from hackerrank: https://www.hackerrank.com/challenges/caesar-cipher-1 . My output matches with the expected output of the program but there is an unknown character at the end of output string.Can someone please tell me how does the unknown character occur at the end of string. Here is my 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;
for (int i = 0; i <n; i++)
{
if(text[i] != '\0') //check if the character is null
{
if(isalpha(text[i])) //check if the character is alphabet
{
int d=(int)text[i] ; //obtain the ascii value
int t=d+k; //obtain the encrypted value
if(t>122) //if the encrypted value of character is greater than 122
{
int extra=t-122;
int letter=97 +(extra-1);
string ans= string()+char(letter);
cout<<ans;
}
string ans= string()+char(t); //print the encrypted character
cout<<ans;
}
else //if the character is not string, then print it just like that
{
cout<<text[i];
}
}
}
}
Sample Output: qmhhpi-Syxd
My Output: qmhhpi-Syxd~
There are few bugs in your code:
if(t>122)
, you are checking if the encrypted character ( by Caesar cypher) has value greater than 122( ASCII for Z). But what if its value was originally in the range AZ and then key was added. int extra=t-122; int letter=97 +(extra-1);
n
, then why are you using if(text[i] != '\\0')
. string ans= string()+char(t); cout<<ans;
. cout << char(t);
The problem is that there are two outputs of string ans
in the loop. So when the current letter is 'z'
(the last letter of your input string) then at first the if statement is executed that prints letter 'd'
and then the statmenets
string ans= string()+char(t); //print the encrypted character
cout<<ans;
are also executed that output the initial value of t.
int t=d+k;
You should use if-else
statement.
Take into account that the code is unsafe very redundant and uses magic numbers like for example 122
that make it unclear.
You should include header <cctype>
because you are using function isalpha
declared in this header.
#include <cctype>
Header <cstdio>
should be removed because none declaration is used from this header.
To output a character there is no need to create an object of type std::string
. For example instead of these statements
string ans= string()+char(t); //print the encrypted character
cout<<ans;
you could just write
cout << char( t );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.