0

The last printf instruction doesn't work with key = 3. I can't understand why, can someone help me? Thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char string[100];
int key;
int jump;
printf("Enter the text: ");
fgets(string, 100, stdin);
printf("Enter crypto key: ");
scanf("%d", &key);
for (int i = 0; i < strlen(string); i++)
{
    jump = 0;
    if (string[i] + key > 126)
    {
        jump = 95;
    }
    string[i] = string[i] + key - jump;
}
printf("The crypto text in key %d is: %s", key, string);
return 0;
}
Arthur
  • 1
  • 1
  • The code involving the variable `jump` looks incomplete. I can easily imagine that, depending on what characters are being encrypted, one of the replaced characters might end up being nonprintable, thus damaging the encrypted string and, making it, well, nonprintable. What input string were you you trying to encrypt with key 3? – Steve Summit Jun 18 '22 at 14:11
  • More importantly, any string you read using `fgets` is likely to end in a newline character, `\n`. And your code is also trying to encrypt that character, turning it into some other control character. For key = 3, you turn `\n` into CR (aka `\r`), a carriage return, which will lead to some weird output. – Steve Summit Jun 18 '22 at 14:15
  • Everything i try to encrypt with key 3 is not printed. Every phrase both with space and without space. – Arthur Jun 18 '22 at 14:15
  • It's because of the carriage return, and the way your environment is displaying it. – Steve Summit Jun 18 '22 at 14:16
  • One fix would be to remove the carriage return after calling `fgets`, and before encrypting. There are many questions here on SO on how to do that. One is [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776). – Steve Summit Jun 18 '22 at 14:16
  • just for that i set the for until i – Arthur Jun 18 '22 at 14:17
  • Who told you `strlen` doesn't count the `\n`? It certainly does. – Steve Summit Jun 18 '22 at 14:18
  • oh so that's the point. Thank you, i'll try to solve it with your advices. – Arthur Jun 18 '22 at 14:20
  • an if i just set the for until i < strlen(string) -1 ? – Arthur Jun 18 '22 at 14:22
  • Yes, that might work. Did you try it? – Steve Summit Jun 18 '22 at 14:26
  • Yeah friend, it works. Thank you so much, i learnt the lesson. – Arthur Jun 18 '22 at 14:28

0 Answers0