问题描述
我正在学习哈佛 CS50x 课程,这是凯撒问题集。
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc,string argv[])
{
if (argc != 2)
{
printf("nope\n");
return 1;
}
int k = atoi(argv[1]);
if (k < 0)
{
printf("nope\n");
return 1;
}
else
{
string code = GetString();
for (int i = 0,n = strlen(code); i < n; i++)
{
if islower(code[i])
printf("%c",(((code[i] + k) - 97) % 26) + 97);
else if isupper(code[i])
printf("%c",(((code[i] + k) - 65) % 26) + 65);
else
printf("%c",code[i]);
}
printf("\n");
return 0;
}
}
我不明白这段代码有什么问题,但是当我尝试编译时,我得到了这个:
解决方法
要使用函数 atoi
,您需要包含标题 <stdlib.h>
#include <stdlib.h>
函数 GetString
似乎没有在头 <cs50.h>
中声明。而是尝试使用函数 get_string
。例如
string code = get_string( "Enter a text: " );
这些 if 语句
if islower(code[i])
printf("%c",(((code[i] + k) - 97) % 26) + 97);
else if isupper(code[i])
不正确。 if 语句中使用的表达式应包含在括号中。例如
if ( islower( ( unsigned char )code[i] ) )
printf("%c",(((code[i] + k) - 97) % 26) + 97);
else if ( isupper( ( unsigned char )code[i] ) )
此外,使用诸如 97
或 65
之类的幻数也是一个坏主意。而是使用 'a'
和 'A'
。