【发布时间】:2020-08-02 23:02:01
【问题描述】:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h> //covert str into int atoi()
#include <ctype.h> // isalpha(), isdigit() etc.
#include <string.h> //strlen() etc.
int main(int argc, string argv[])
{
// convert argv[1] into int
int key = atoi(argv[1]);
// if input is 2 command lines and argv > 0 and there is no alphabet n shit in argv[1] we good to go
if (argc == 2 && key > 0 && isdigit(argv[1]))
{
//ask for input to chiper
string plain = get_string("Plaintext: ");
int len_plain = strlen(plain);
// check each char in string plain
for (int i = 0; i < len_plain; i++)
{
// if its from 'a' to 'z' add number of key
if (plain[i] >= 'a' && plain[i] <= 'z')
{
char cipher = (plain[i] + key) % 26;
printf("%c", cipher);
return 0;
}
}
}
else
{
printf("Usage: ./caesar kay");
return 1;
}
}
运行此代码时,我遇到了分段错误。我做错了什么?我已经在这段代码上工作了几天,但我无法让它工作。
【问题讨论】:
-
不是每个试图回答这个问题的人都可以访问
cs50.h。你能请吗?从代码中删除该依赖项。另外,isdigit的参数不应该是一个字符吗? (即isdigit(argv[1][0])) -
编译器应该会告诉您您将不正确的参数类型输入到
isdigit。打开警告并处理它们。
标签: c segmentation-fault cs50