Home > Software design >  PSET2 Caesar: Ordered Comparison Between Pointer and Integer Error
PSET2 Caesar: Ordered Comparison Between Pointer and Integer Error

Time:09-08

I am currently taking Harvard's CS50 course (Intro to CompSci). I have not even learned pointers yet, I am confused on this error message. The line it is facing an error on in question is this: For context, the full message is as follows:

caesar.c:48:36: error: ordered comparison between pointer and integer ('string' (aka 'char *') and 'char') [-Werror] if (plaintext[j] key > z)

So, I am unable to understand the error message due to not yet being educated on pointers. Help50 is useless when I compiled with it. Here is my code if it is needed, I hope the comments help!

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

int main(int argc, string argv[])
{
    //Creates string key
    string key = argv[1];
    //Checks for appropriate argument count
    if (argc != 2)
    {
        printf("Usage: ./caesar key");
        return 1;
    }
    //Checks if all argument characters are digits
    for (int i = 0; i < strlen(key); i  )
    {
        if (isdigit(key[i]) == 0)
        {
            printf("Usage: ./caesar key");
            return 1;
        }
    }

    //Gets plaintext from user
    string ciphertext = NULL;
    char z;
    string plaintext = get_string("plaintext:  ");

    //Converts plaintext to ciphertext
    for (int j = 0; j < strlen(plaintext); j  )
    {
        //Asks if character is alphabetical
        if (isalpha(plaintext[j]))
        {
            //Asks if character is uppercase and assigning ASCII code accordingly
            if (isupper(plaintext[j]))
            {
                z = 90;
            }
            else
            {
                z = 122;
            }

            //Performs conversion operation
            if (plaintext[j]   key > z)
            {
                ciphertext[j] = plaintext[j]   key - 25;
            }
            else
            {
                ciphertext[j] = plaintext[j]   key;
            }
        }
        //Keeps text the same since it is not a letter, and therefore shouldn't be shifted
        else
        {
            ciphertext[j] = plaintext[j];
        }
    }

    printf("ciphertext: %s\n", ciphertext);
}

Thank you!

CodePudding user response:

//Creates string key
string key = argv[1];

key is a "string", not an integer value.

if (plaintext[j]   key > z)

The code is attempting to add a char to a string, then compare that to a char.

You need to go back to the basics and review the lesson until you understand arrays of characters and strings.

string ciphertext = NULL;

Here, you initialise a string, then seem to expect it to somehow grow as you later write characters into that string.

Sit down with a paper and pencil and diagram out what you expect to be happening with memory storage...

  • Related