DescX
DescX

Reputation: 334

blank spaces in a string

I have a text that's encrypted in Caesar's Cipher.

Using fgets i'm storing all the text in a buffer. Untill here the data is in it's original form, with spaces between the text.

Now when I'm looping through the text and shifting the letters my output has all the spaces removed while i did not alter any text.

Here is my code:

int main(){
    char *buff;

    FILE *filePtr = fopen("text.txt", "r");

    fgets(buff, BUFF, filePtr);

    decrypt(buff);
}

void decrypt(char *s){
    int i, a, l;
    a = 3;
    l = strlen(s);

    for (i = 0; i < l; i++){
            if (!isalpha(s[i]))
                    continue;
            printf("%c", s[i] - 3);
    }

    printf("\n");
}

Now can anyone explain me why the spaces are gone in my output?

Upvotes: 2

Views: 126

Answers (1)

Vality
Vality

Reputation: 6607

I have not actually run the code so this is largely from the top of my head, but in my best guess I would say that space is likely not passing the isalpha check so is being skipped, you need to add a second check for chars which are not letters to be shifted but should still be printed. For example:

int main(){
    char *buff;

    FILE *filePtr = fopen("text.txt", "r");

    fgets(buff, BUFF, filePtr);

    decrypt(buff);
}

void decrypt(char *s){
    int i, a, l;
    a = 3;
    l = strlen(s);

    for (i = 0; i < l; i++){
            if (isalpha(s[i]))
                printf("%c", s[i] - 3);
            else if (isprint(s[i]))
                printf("%c", s[i]);
    }

    printf("\n");
}

Upvotes: 1

Related Questions