我是新来的。我想为“CS50 Caesar”问题找到一个解决方案。 详细信息:https://cs50.harvard.edu/x/2024/psets/2/caesar/
I'm getting these as feedback:
:) 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
timed out while waiting for program to exit
:) handles too many arguments
我该如何解决 ":( 处理非数字键 等待程序退出时超时” 这条线?
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./ceasar key\n");
return 1;
}
if (atoi(argv[1]) == 0)
{
printf("Usage: ./ceasar key\n");
return 1;
}
int k = atoi(argv[1]);
k = k % 26;
string plaintext = get_string("plaintext: ");
string ciphertext = plaintext;
int n = strlen(plaintext);
for (int i = 0; i < n; i++)
{
if ('a' <= plaintext[i] && plaintext[i] <= 'z')
{
if ((plaintext[i] + k) > 'z')
{
ciphertext[i] = ((plaintext[i] + k) - 26);
}
else
{
ciphertext[i] = (plaintext[i] + k);
}
}
else if ('A' <= plaintext[i] && plaintext[i] <= 'Z')
{
if ((plaintext[i] + k) > 'Z')
{
ciphertext[i] = ((plaintext[i] + k) - 26);
}
else
{
ciphertext[i] = (plaintext[i] + k);
}
}
}
printf("ciphertext: %s\n", ciphertext);
return 0;
}
我该如何解决 ":( 处理非数字键 等待程序退出时超时” 这条线?
使用
strtol()
来验证和转换 argv[1]
而不是 atoi()
。
// int k = atoi(argv[1]);
errno = 0;
char *endptr;
long lvlaue = strtol(argv[1], &endptr, 0);
if (argv[1] == endptr) {
// No conversion
print error and exit
}
if (*endptr != 0) {
// Trailing junk conversion
print error and exit
}
if (errno || lvalue < INT_MIN || lvlaue > INT_MAX) {
// Out of range
print error and exit
}
k = (int) lvalue;