【发布时间】:2018-06-17 09:30:01
【问题描述】:
我正在尝试CS50 Vigenere exercise。
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[])
{
//Check for 2 command line arguments
if (argc != 2)
{
printf("Nah bro, you gotta have 2 arguments.\n");
return 1;
}
//Check is alpha
else {
for (int i = 0; i < strlen(argv[1]); i++)
{
if (isalpha(argv[1][i]) == 0)
{
printf("Nah bro, u gots to use letters.\n");
return 1;
}
}
}
//Prompt user to input text
printf("plaintext: ");
string p = get_string();
//Cipher
printf("ciphertext: ");
string k = argv[1];
int cipherlen = strlen(k);
//Cycle through key letters
for (int i = 0, j = 0, n = strlen(p); i < n; i++)
{
if (isalpha(p[i]))
{
if (isupper(p[i]))
{
printf("%c", ((p[i] - 65) + (k[(j % cipherlen)]) - 65) % 26 + 65);
j++;
}
else if (islower(p[i]))
{
printf("%c", ((p[i] - 97) + (k[(j % cipherlen)]) - 97) % 26 + 97);
j++;
}
else
printf ("%c", p[i]);
}
}
printf("\n");
return 0;
}
根据检查,这是我的错误代码:
https://cs50.me/checks/a56bc9325327035cb0e8d831693c9805c4b6468b
我知道我的问题与循环遍历每个字母有关,但没有将其应用于空格或符号。我尝试使用 if (isalpha) 语句和 else printf(" ") 但它不适用于数字或符号。我认为添加 j++ 只会遍历字母字符,但它似乎没有帮助。
这里有什么我错过的超级简单的东西吗?
【问题讨论】:
-
"string" 好像是"char *" 类型,所以应该没问题...
-
@melpomene 它应该适用于 ascii 代码
-
@LeoH 你应该使用
isprint()而不是isalpha()来输出"$!等字符。