cstringencryption

Fill empty C string correctly


I am trying to implement the "hebrew encryption", which works as follows:

Example:

This
is an
exam
ple..

However, I have trouble with text that is shorter than the array has space:

This 
is an

 ????

Where '?' are random(?) characters.

My guess is, that I do not format the string correctly. Currently I check whether a character is '\n' or '\0' and replace it with a whitespace.

Any help is appreciated.

My code looks like this:

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

int main(void){
    int x, y; 
    
    printf("Please input rows and columns: \n");
    scanf("%d", &x);
    scanf("%d", &y);
    char string[x*y];

    printf("Please insert text: \n");
    fgets(string, x*y, stdin);              //ignore \n from previous scanf (otherwise terminates
    fgets(string, x*y, stdin);              // immediately as \n is still there)

    int k = 0;
    char code[y][x];
    for(int i=0; i < x*y; i++){
        if(string[i] == '\n' || string[i] == '\0')
            string[i] = ' ';
    }
    for(int i=0; i < y; i++){
        for(int j=0; j < x; j++){
            code[i][j] = string[k];
            k++;
        }
    } 

    //output of matrix
    for(int i=0; i < y; i++){
        for(int j=0; j < x; j++){
            printf("%c ",code[i][j]); 
        }
        printf("\n");
    } 

    //matrix to message
    k = 0;
    char message[128];
    for(int j=0; j < x; j++){
        for(int i=0; i < y; i++){
            message[k] = code[i][j];
            k++;
        }
    } 

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

    return 0;
}

Solution

  • nul pad the string then wen reading out the result skip the nuls

    char string[x*y+1]; // you had it too small

    ...

        fgets(string, x*y+1, stdin);              //immediatly as \n is still there)
        int num_read = strlen(string);
        if(num_read < x*y+1 )
           memset(string+num_read,'\0',x*y+1-num_read);
        if (string[num_read ] == '\n' )
            string[num_read ] = '\0';
    

    ...

        char message[x*y+1];  // was way too small!
        for(int j=0; j < x; j++){
            for(int i=0; i < y; i++){
                if(code[i][j])
                  message[k] = code[i][j];
                k++;
            }
        } 
        message[k]='\0'