-1

I am trying to encrypt a string by Caesar encryption, but it only works for one word (no spaces between characters). I would like to encrypt whole sentence. I have read here about getting white spaces from keyboard into a string by gets() or fgets(), but I cannot make it functional.

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

int main(int argc, char** argv) {
    printf("Enter the shift: ");
    int shift,index,length;
    scanf("%d", &shift);

    printf("Enter the string to encrypt: " );
    char string[1000];
    //gets(string);
    scanf("%s",string);
    //fgets(string,1000,stdin);

    char encrypted[strlen(string) + 1];

    for(index = 0, length = strlen(string); index < length; index++ ){
        if (string[index]!=' ')
            encrypted[index] = 'A' + (string[index] -'A' + shift) % 26;
        else
            encrypted[index]=' ';
    }
    encrypted[ strlen(string)] = '\0';

    printf("%s\n", encrypted);

    return (EXIT_SUCCESS);
}
Dounchan
  • 319
  • 3
  • 10

3 Answers3

1

In

char string[1000];
scanf("%s",string);

the scan terminates at whitespace.

To get the whole string (excluding the trailing newline) use:

char string[1000], *p;
fgets(string, sizeof(string), stdin);
if ((p = strchr(string, '\n')) != NULL) { 
    *p = '\0'; /* remove newline */
}

As pointed out by @chux you need to consume \n in scanf, I suggest:

int shift, index, length;
char string[1000], *p;

fgets(string, sizeof(string), stdin);
shift = atoi(string);
printf("Enter the string to encrypt: " );
fgets(string, sizeof(string), stdin);
if ((p = strchr(string, '\n')) != NULL) { 
    *p = '\0'; /* remove newline */
}

And you get:

Enter the shift: 1
Enter the string to encrypt: MY NAME
NZ OBNF
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

You're using scanf("%s",string);. That stops as soon as it hits whitespace. Instead, use

fgets(string, sizeof(string), stdin);

(Note that it's not a great idea to allocate a large string with something like char string[1000]; -- in most implementations, it goes on the stack. malloc is better.)

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
0

The remaining line breaks without being consumed in the part of scanf("%d", &shift).
So, it appears that fgets and gets you to enter a new line up to not function.(Because they are given a new line remaining)

while(getchar()!='\n');//get rid of the newline up
scanf("%999[^\n]", string);//It corresponds to the `gets()`
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70