Sorry, I know this has been asked before but I have read all the answers and nothing works! Please help. When I check acutal and expected outputs, they match, but in check50 It gives an error message. Here is the link for check50 results: https://submit.cs50.io/check50/6d939efb8a55e3fadec1c60952311f6198cd0eb0
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char crypt(int k,char w)
{
if ('a'<= w && w <='z')
{
return (((w-'a') k)& 'a');
}
else if ('A' <= w && w <= 'Z')
{
return (((w -'A') k) % 26 'A');
}
else
{
return (w);
}
}
int main(int argc, string argv[])
{
//input check
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
int lngg = strlen(argv[1]);
for (int i = 0; i < lngg; i )
{
if (isdigit(argv[1][i]) == 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
}
int key = atoi(argv[1])&;
//input
string plain = get_string("plaintext: ");
//crpypt starts
printf("ciphertext: ");
int lng = strlen(plain) 1;
for (int a = 0; a < lng ;a )
{
printf("%c", crypt(key, plain[a]));
}
printf("\n");
}
Hi, When I look expected and actual outputs, everything seems perfect but it errors
CodePudding user response:
The problem is that you are also printing the terminating null character to standard output using printf
. This character is not printable, so you cannot see it, but check50
does detect it and therefore reports that your program failed.
The loop
for(int a=0; a<lng ;a )
{
printf("%c",crypt(key,plain[a]));
}
will run for strlen(plain) 1
iterations, because that is the value to which you set the variable lng
.
You should instead set the value of lng
to strlen(plain)
, in order to prevent the terminating null character from being printed.
CodePudding user response:
@w is correct.
Also, code can avoid 2 passes down the string and do only 1.
// int lng = strlen(plain) 1;
// for (int a = 0; a < lng ;a )
for (int a = 0; plain[a] != '\0'; a )