1

Below is my code and it is working for 10/11 checks, but shows the error message for this one: :( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key Cause expected "ciphertext: ia...", not "ciphertext: ia..."

Log running ./caesar 12... sending input world, say hello!... checking for output "ciphertext: iadxp, emk tqxxa!\n"...

Expected Output: ciphertext: iadxp, emk tqxxa! Actual Output: ciphertext: iadxp, emk tqxxa!

I have no idea why as they look identical to me, what obvious error am I missing here??

#include <ctype.h> 
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main(int key, string word[])
{
//Ensure only a key of 2 is accepted   
if (key != 2) 
{   
    printf("Usage: ./caesar key\n");
    return 1;
}
//Ensure the second input has has no letters.  
for (int i = 0, n = strlen(word[1]); i < n;)

    if (isalpha(word[1][i]))
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    //Ensure each character of the input is a digit  
    else if (isdigit(word[1][i]))
    {
        i++;
    }
    else
    {
      printf("Usage: ./caesar key\n");
        return 1;
    }
    
string text = get_string("Plain text: ");

{
    printf("ciphertext: ");
}

{  
 //check each character is an alphabetical one
    for (int b = 0, n = strlen(text); b < n; b++;)
    { 
        int k = 0;
        int cipher = 0;
         
        if(!isalpha(text[b]))
        
        {  
            printf("%c", text[b]);
        }   
        
        else if (isalpha(text[b]))

        {
  //Calculate the cipher code for a lower-case letter        
            if (islower(text [b]))
            { 
                int t = text [b] - 97;
                k = (t + atoi(word[1])) % (26);
                cipher = k + 97;
  //Calculate the cipher code for an upper-case letter              
            }
            else if (isupper(text[b]))
      
            {
                int t = text [b] - 65;
                k = (t + atoi(word[1])) % (26);
                cipher = k + 65;
            }
        }
 
          
  
 //print cipher text.       
        {
            printf("%c", cipher);
        }
    }
    
    printf("\n");

 
} 

}

user250888
  • 11
  • 1

1 Answers1

0

First, to see what check50 sees, try this on the failing input.

./caeser 12 | cat -v

cat -v displays unprintable characters. The unprintable characters are coming from here printf("%c", cipher);. That line executes whether the input (text[b]) is alpha or not. That line needs to move inside the else if (isalpha(text[b])) block.

DinoCoderSaurus
  • 6,110
  • 2
  • 10
  • 15