Saara Luthra
Saara Luthra

Reputation: 29

Caesar, detecting something wrong with the key

Code:

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

int main(int argc, string argv[])
{
    int key = 0;
    string plaintext;
    if (argc != 2) 
    {
        printf("Usage: ./caesar key \n");
    }
     else  
    {
        key = atoi(argv[1]);
        plaintext = get_string("Plaintext: ");
        printf("\n");
        printf("Ciphertext: ");
        
        for (int j = 0, n = strlen(plaintext); j < n; j++)
        {
            if (isupper(plaintext[j]))
            {
               printf("%c", (((plaintext[j] + key) - 65) % 26) + 65);
            }
            else if (islower(plaintext[j]))
            {
                printf("%c", (((plaintext[j] + key) - 97) % 26) + 97);
            }
            else 
            {
                printf("%c", plaintext[j]); 
            }
        }
        printf("\n");
    }
}
    

Run log:

~/pset2/caesar/ $ ./caesar 1
Plaintext: a

Ciphertext: b

I am working on pset2, caesar.

How can I check if my key is numerical or not?

I have tried many ways but failed, does someone know of a way I can do that? I am a beginner.

Upvotes: 0

Views: 88

Answers (1)

chux
chux

Reputation: 154087

How can I check if my key is numerical or not?
I need to use strtol() to check whether my key is numerical or not?

Use strtol().

char *endptr;
errno = 0;  // Set to zero to later detect if `long` overflow 
            // or other implementation specific error occurred.
long key = strtol(argv[1], &endptr, 10);
//                                  ^^ base 10 number
//                         ^-----^     address to store end of conversion    

if (argv[1] == endptr) {
  puts("No conversion");
} else if (errno) {
  puts("Overflow");
} else if (*endptr != '\0') {
  puts("Junk after a number");
} else {
  printf("Success");
}

Maybe more tests to see if key in a sane range like 0 to 100 or whatever.

It is good that OP had a prior if (argc != 2) test to filter out (indirectly) argv[1] == NULL.

Upvotes: 1

Related Questions