Skip to content

Instantly share code, notes, and snippets.

@wx5162839
Last active May 4, 2020 09:45
Show Gist options
  • Select an option

  • Save wx5162839/dc2fb54c0ba46a732bbba068caca9e4b to your computer and use it in GitHub Desktop.

Select an option

Save wx5162839/dc2fb54c0ba46a732bbba068caca9e4b to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
//if agrv[1] is not number, atoi(agrv[1]=0;
//however, need to add !isdigit(argv[1]),
//because Your return 1; will immediately end the program (ie, if the first character is a digit, your program will print success)
//so no further characters are checked.
//The function atoi(const char *) will read characters from a string until it hits a non-digit character.
//That's why 20x succeeds, but x20 fails. With 20x it reads 2 then 0 then stops. With x20 it just hits the x and then stops.
if (argc!=2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//if input equals "./caesar 20x", the output still not equals "Usage: ./caesar key".
//isdigit(*argv[1]) will only determine whether the string argv[1] starts with a digit or not, it doesn't apply to the full string.
for (int a=0, b=strlen(argv[1]); a<b; a++)
{
if(!isdigit(argv[1][a]))
{
printf("Usage: ./caesar key\n");
return 1;
}
}
string p = get_string("plaintext: ");
printf("ciphertext: ");
int k = atoi(argv[1]);
//int k = atoi(argv[1]) can not be in the top;
//the mistakes is in the above assignment, if the there is no argv[1] so the OS will report error and terminates the program,
//so you have not to do k assignment to argv[1] unless you make sure there is argv[1].
int m = k%26;
for (int i=0, j=strlen(p); i<j; i++)
{
if (p[i]<='Z'&&p[i]>='A')
{
if (p[i]+m<='Z')
{
printf("%c", p[i]+m);
}
else
{
printf("%c", p[i]+m-26);
}
}
else if (p[i]<='z'&&p[i]>='a')
{
if (p[i]+m<='z')
{
printf("%c", p[i]+m);
}
else
{
printf("%c", p[i]+m-26);
}
}
else
{
printf("%c", p[i]);
}
}
printf("\n");
return 0;
}
//segmentation fault reason:
//a segmentation fault happens when you touch a memory location that you shouldn't touch.
//more likely is that you're passing a string instead of a char to a function that accepts a char (e.g., isalpha())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment