#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;
}
}
When running this code, I'm faced with a segmentation fault. What did I do wrong? I have been working a few days on this code but I cannot make it work.
This isdigit(argv[1])
is giving a seg fault. The function signature of isdigit
(from the man page):
int isdigit(int c);
But, argv[1]
(if it exists.) is a string. Suggest you follow the spec by
Only then are you assured that atoi
will give the desired result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.