CS50 ps2. The command check50 returns error message "non numeric code"

130 Views Asked by At

I wrote CS50 course's the caesar task's code. Everything is working excellent. But when I run the command check50, in the response there is a mistake. When the input is not-numeric my code returns 0 and terminates the program. But the response is that it returns 1. Here is my code and the response. Please help to solve this problem. Thank you in advance

-The response

:) caesar.c exists.
:) caesar.c compiles.
:) encrypts "a" as "b" using 1 as key
:) encrypts "barfoo" as "yxocll" using 23 as key
:) encrypts "BARFOO" as "EDUIRR" using 3 as key
:) encrypts "BaRFoo" as "FeVJss" using 4 as key
:) encrypts "barfoo" as "onesbb" using 65 as key
:) encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key
:) handles lack of argv[1]
:( handles non-numeric key
    expected exit code 1, not 0
:) handles too many arguments

-My code

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

bool only_digits(string st);
char change (char a, int key);

int main(int argc, string argv[])
{
   if (argc == 2)
   {
       if(only_digits(argv[1]))
       {
           string plaintext = get_string("plaintext:  ");
           int key = atoi(argv[1]);
           printf("ciphertext:  ");
           for (int i = 0; i < strlen(plaintext); i++)
           {
                printf("%c", change(plaintext[i], key));
           }
           printf("\n");
       }
       else
       {
           printf("a\n");
           return 0;
       }
   }
   else
   {
       printf("b\n");
        return 1;
   }
}


bool only_digits(string st)
{
    int d = 0, o = 0;
    for (int i = 0; i < strlen(st); i++)
    {
        if (isdigit(st[i]))
        {
            d++;
        }
        else{
            o++;
        }
    }
    if (o>0)
    {
        printf("%i\n", o);
        return 0;
    }
    else{

        return 1;
    }
}

char change (char a, int key)
{
    if(isalpha(a))
    {
       if(islower(a))
        {
            int lettercode = a-97;
            int check = (lettercode + key);
            if(check<26){
                char changed = check + 97;
                return changed;
            }
            else
            {
                char changed = (check % 26) + 97;
                return changed;
            }
        }
        else
        {
            int lettercode = a-65;
            int check = (lettercode + key);
            if(check<26){
                char changed = check + 65;
                return changed;
            }
            else
            {
                char changed = (check % 26) + 65;
                return changed;
            }
        }
    }
    else
    {
        return a;
    }
}
0

There are 0 best solutions below