我正在为作业制作基本密码,并尝试确保密码仅适用于Alpha文本。建议我使用" isalpha()"为此,我在下面的代码中尝试了这个:
if( isalpha(cipherInput))
{
for (int i = 0, n = strlen(cipherInput); i < n; i ++)
{
printf("%c", (cipherInput[i] + k % 26));
}
}
else
{
printf("%s\n", cipherInput);
}
这返回&#34;分段错误(核心转储)&#34;当我尝试输入任何东西时,我做了一些谷歌搜索,并找到了如何调试,返回
Core was generated by `./caesar 3'.
Program terminated with signal 11, Segmentation fault.
#0 0x0804879e in main (argc=2, argv=0xbfd14604) at caesar.c:21
21 if( isalpha(cipherInput))
(gdb) ^CQuit
这显然意味着我以奇怪的方式搞乱内存堆栈。为什么这会从简单的if语句中发生?我在网上找到的所有例子都涉及指针。
这里是完整的代码:
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[])
{
int k = atoi(argv[1]);
if( k <= 0 )
{
printf("You must input a non-negative integer.\n");
return 1;
}
printf("What do you want to cipher?\n");
string cipherInput = GetString();
if( isalpha(cipherInput))
{
for (int i = 0, n = strlen(cipherInput); i < n; i ++)
{
printf("%c", (cipherInput[i] + k % 26));
}
}
else
{
printf("%s\n", cipherInput);
}
printf("\n");
}
注意:cs50.h
可以在http://dkui3cmikz357.cloudfront.net/library50/c/cs50-library-c-3.0/cs50.h