0

So under "Peeking under the hood" they asked to ignore the key the user provided and instead prompt the user for a plaintext and move each character by 1. when I run my program, and input "hello" as the plaintext it prints out " p" with a space in front of the p instead of "ifmmp"

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

char encipher_text(string plaintext);

int main(int argc, string argv[])
{
    if (argc == 2 )
{
    // Check if all the chars in the argument are decimal digits
    
    string arg = argv[1];
    for (int i = 0, n = strlen(arg); i < n; i++)
    {

        if (!isdigit(arg[i]))
        {

            printf ("Usage: ./caesar key\n");
            return 1;
        }

    }
    int key = atoi(arg);
    
    // Get text from user
    string plaintext = get_string("plaintext: ");
    char ciphertext = encipher_text(plaintext);
    printf("ciphertext: %c\n", ciphertext);
    
    

}
else
{
    printf ("Usage: ./caesar key\n");
}
}

char encipher_text(string plaintext)
{
    char ciphertext = 0;
    for (int i = 0, n = strlen(plaintext); i < n; i++)
    {
    
       ciphertext = plaintext[i] + 1;
       
    }
    return ciphertext;
    
    }
1

You have a logic error in your declaration of ciphertext. Take a look at how it is declared (it's type) and the type of plaintext. ;)

This should hopefully make it clear why one seems to work with multiple letters and the other only one.

If this helps, feel free to click the check mark. But if not, let me know and I will help further.

2
  • I tried that but it says, "incompatible integer to pointer conversion assigning to 'string' (aka 'char *') from 'int' " when I change the type to match the plaintext's type in line 50 ciphertext = plaintext[i] + 1; – ehsansth Mar 16 at 11:47
  • 1
    That's because you can't make an entire string equal to plaintext[i] + 1. You'll need to make more modifications than just changing the type of ciphertext to make your code work. The reason it only prints a single letter is because it is of the char type. You need to think about how you want to assign values to ciphertext and if any type conversions need to happen before ciphertext can accept it. – Robert S. Pratt Mar 16 at 12:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .