简体   繁体   中英

C Vigenere Cipher Not Printing

I've been tasked with creating a vigenere cipher, but my program is not printing out anything. Thing is, I'm not sure where the problem is; is the file not reading in, is my logic incorrect, etc.? Any help as to where I messed is appreciated.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void encrypt(char *theString, int shift)
{

    if (isalpha(*theString) && isupper(*theString))
    {

            *theString += shift;
            if (*theString >= 'Z')
            {
                    *theString = *theString - 26;
            }


    }

    theString++;

}


int main(void)
{

    FILE *inputFile;
    char KEY[256];
    char theString[80];
    int shift;
    int i;

    inputFile = fopen("code.txt", "r");
    if (inputFile == NULL)
    {
            printf("Failed to open\n");

            return(0);

    }
    fgets(theString, sizeof(theString), stdin);

                   printf("Enter the Key: ");
    fgets(KEY, sizeof(KEY), stdin);
    for (i = 0; i < 256; i++)
    {

            shift = KEY[i] - 65;
            encrypt(theString,shift);
            puts(theString);
    }
    return(0);


}

The reason you're not seeing any output is because this happens first:

fgets(theString, sizeof(theString), stdin);

That reads a string from standard input, and waits until you press Enter . So it looks like the program is stuck. You should print a prompt first, such as:

printf("Enter a string: ");

Your encrypt loop only modifies the first character of the input string. You need a loop to modify every character:

void encrypt(char *theString, int shift)
{
    for ( ; *theString != '\0'; theString++)
    {
        if (isupper(*theString))
        {
            *theString += shift;
            if (*theString >= 'Z')
            {
                *theString = *theString - 26;
            }

        }
    }
}

Other points:

  • isupper() implies isalpha() ; no need for both
  • fgets() returns NULL on error; you should check for it

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM