Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdlib.h>
- int shift(char c);
- int main(int argc, string argv[])
- {
- if (argc != 2) //if user doesn't run command-line argument of one or enter positive int
- {
- printf("Usage: ./vigenere key\n"); //prompt them to run it again
- return 1; //returning zero means everything went well
- }
- for (int j = 0, n = strlen(argv[1]); j < n; j++) //length of the entire string. Save n as strlen for use in loop
- {
- if (isalpha(argv[1][j])) //if user doesn't run command-line argument of one or enter positive int and user inputs an alpha key, continue
- {
- //printf("%c\n", argv[1][j]); //Print after collecting plaintext
- }
- else
- {
- printf("Usage: ./vigenere key\n"); //prompt them to run it again
- return 1; //returning zero means everything went well
- }
- }
- string p = get_string("plaintext: "); //prompt for plaintext and store
- string key = argv[1]; //declare the key as a string
- char cipher; //declare cipher as a char
- //NOW ROTATE BY THE KEY
- for (int i = 0; i < strlen(p); i ++) //length of the entire string
- {
- if (j == strlen(key))
- {
- j = 0;
- }
- if (isupper(p[i]))
- {
- cipher = (((p[i] + shift(key[j])) - 65) % 26) + 65; //Use the new shift function now
- printf("ciphertext: %c", cipher); //print ciphertext after rotating
- j++;
- }
- else if (islower(p[i]))
- {
- cipher = (((p[i] + shift(key[j])) - 97) % 26) + 97; //add key and rotate
- printf("ciphertext: %c", cipher); //print ciphertext after rotating
- j++;
- }
- else
- {
- printf("ciphertext: %c", p[i]);
- }
- }
- printf("\n");
- return 0;
- } //Closing braces
- //function definition
- int shift(char c); //NEW SHIFT function
- {
- int k;
- if (islower(c))
- {
- k = c - 97;
- }
- if (isupper(c))
- {
- k = c - 65;
- }
- return k;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement