【发布时间】:2019-11-13 06:48:35
【问题描述】:
在过去的一个月里,我是一个完全的新手,非常努力地使用这个 pset。充其量我有以下内容,但这不起作用。
我认为我的移位函数没问题,我知道目前它被写入最后打印整数,但即使是整数也不是正确的 ASCII。
如果你运行代码,即使明文的长度只有 3 个字符,它也会输出四个整数。请告诉我你的想法?
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int shift (char c); // declaring prototype of a function that converts char into shift value
int main(int argc, string argv[]) // Counting command-line arguments
{
if (argc == 2)
{
string s = argv[1]; // string of user's key
int l = 0;
while (s[l] != '0')
{
l++
}
int i = 0 // validating user's key
while (i < l)
{
if (isalpha(s[i]))
{
i++;
}
else
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
}
string plaintext = get_string("plaintext: "); // prompt for plaintext
{
printf("ciphertext: ");
for (int a = 0, n = strlen(plaintext); a < n; a++)
{
int key = shift(s[l]);
int ciphertext = (int)plaintext[a];
{
printf("%i + %i", ciphertext, key);
}
l++;
}
printf("\n");
}
}
else
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
}
int shift(char c) // Fx shift: getting the integer of key for each char
{
int key = (int)c;
if (65 <= key && key <= 90)
{
return (key - 65);
}
else if (97 <= key && key <= 122)
{
return (key - 97);
}
else
{
return 1;
}
}
【问题讨论】:
-
CS50
string的元素不能安全地与isalpha()等函数一起使用。string只不过是一个混淆的char *,而诸如isalpha()之类的函数采用int参数。在带有签名的char的实现上,值将在传递给isalpha()et 之前进行符号扩展。 al.,并且没有正确解释。这是另一个理由放弃 CS50 的愚蠢string。