简体   繁体   中英

Using modulo to loop 9-0 and printing

Currently I am having an issue in my program where I am trying to have a very basic encryption method that if 5 is entered, 9 is printed. I am trying to make it loop so that z will become d, and 9 will become 3. I have currently got it adding 4, but it is not doing the loop from 9-0 for integers, for letters it is working fine.

Below is a piece of code that is made from elements of my code to reproduce what is happening.

#include <stdio.h>
#include <conio.h>

int main()
{

int i, j;
char password[9];


printf("Please enter a password:\n\n");
scanf("%8c", &password);



for(i = 0; i < 8; i++)
    {
        if(password[i] >= '0' && password[i] <= '9')
        {
            password[i] = (char)(password[i] + 4 % 10);
        }

        if((password[i] >= 'a' && password[i] <= 'z') || (password[i] >= 'A' && password[i] <= 'Z') )
        {
            password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');
        }
    }

    for(j =  0; j < 8; j++)
    {
        printf("%c", password[j]);
    }

}

You have to handle the numbers and the letters identically. You have:

        password[i] = (char)(password[i] + 4 % 10);
        ...
        password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');

You need to subtract and add '0' for numbers, just like you do with 'a' for letters:

        password[i] = (char)((password[i] - '0' + 4) % 10 + '0');
        ...
        password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');
  • password[i] + 4 % 10 is always equals to password[i] + 4 since the precedence of % is higher one of + .
  • scanf("%8c", &password); causes undefined behavior due to type mismatch. Remove the & and write it as scanf("%8c", password); .
  • You should deal with uppercase letters and lowercase letters separately because for example 'A' - 'a' + 4 becomes negative value if you use ASCII code and then the result will be what you won't want.

Try this:

#include <stdio.h>

int main(void)
{

    int i, j;
    char password[9] = "{0}";

    printf("Please enter a password:\n\n");
    scanf("%8c", password);

    for(i = 0; i < 8; i++)
    {
        if(password[i] >= '0' && password[i] <= '9')
        {
            password[i] = (char)((password[i] + 4) % 10);
        }

        if(password[i] >= 'a' && password[i] <= 'z')
        {
            password[i] = (char)((password[i] - 'a' + 4) % 26 + 'a');
        }

        if(password[i] >= 'A' && password[i] <= 'Z')
        {
            password[i] = (char)((password[i] - 'A' + 4) % 26 + 'A');
        }
    }

    for(j =  0; j < 8; j++)
    {
        printf("%c", password[j]);
    }

    putchar('\n');
    return 0;
}

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