问题
I finished pset2 (caesar) of CS50, but when I run it through check50, I get three errors, each involving the command-line arguments in some way. When I try to test it myself, it works fine, which makes me think the problem is "under the hood" and not able to be solved unless I revise my code. I tried deleting uncessary lines, but the errors still persisted, so I was wondering if someone could take a look at my code and tell me what's wrong.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int check_key(int argc, string argument);
string plain_cipher(string plaintext, int key);
int main(int argc, string argv[])
{
// checks if there are only 2 cl-arguments + if there are any alpha characters (uses function: check_key)
if (argc != 2 || argc == 1)
{
printf("Usage: ./caesar key\n");
}
else
{
string input = argv[1];
int key = check_key(argc, input);
if (key == 0)
{
printf("Usage: ./caesar key\n");
}
else
{
string plaintext = get_string("plaintext: ");
string ciphertext = plain_cipher(plaintext, key);
}
}
}
int check_key(int argc, string argument)
{
int i;
int j = 0;
char letter = argument[0];
for (i = 0; i < strlen(argument); i++)
{
letter = argument[i];
if isalpha(letter)
{
j++;
}
}
if (j >= 1)
{
return 0;
}
else
{
int key = atoi(argument);
return key;
}
}
string plain_cipher(string plaintext, int key)
{
string ciphertext = "ciphertext: ";
printf("%s", ciphertext);
int i = 0;
for (i = 0; i < strlen(plaintext); i++)
{
char letter = plaintext[i];
if isalpha(letter)
{
if isupper(letter)
{
char enc_letter_upper = (letter - 65 + key) % 26;
enc_letter_upper += 65;
printf("%c", enc_letter_upper);
}
else
{
char enc_letter_lower = (letter - 97 + key) % 26;
enc_letter_lower += 97;
printf("%c", enc_letter_lower);
}
}
else
{
printf("%c", letter);
}
}
printf("\n");
return ciphertext;
}
And here's the check50 output:
:) 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 key
expected exit code 1, not 0
:( handles non-numeric key
expected exit code 1, not 0
:( handles too many arguments
expected exit code 1, not 0
The error shown for all three failures is "expected exit code 1, not 0", but I'm not quite sure what that actually means, so I was hoping someone could elaborate/revise my code. Thanks in advance :)
来源:https://stackoverflow.com/questions/61993032/cs50-caesar-program-pset2-runs-but-outputs-errors-in-check50-expected-exit-c