正确填充空C字符串

时间:2015-01-07 11:04:45

标签: c string encryption

我正在尝试实施“希伯来语加密”,其工作原理如下:

  • 输入列数和行数
  • 输入要加密的文字
  • 用文字填充数组
  • 首先输出文本列

示例:

  • 5 by 4:“这是一个例子..”
This
is an
exam
ple..
  • 输出:“Ti phseli xesaa.nm。”

但是,我遇到的文本短于数组有空格的问题:

  • 5 by 4:“这是一个”
This 
is an

 ????

哪里'?'是随机(?)字符。

我的猜测是,我没有正确格式化字符串。目前我检查一个字符是'\ n'或'\ 0'并用空格替换它。

感谢任何帮助。

我的代码如下所示:

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

int main(void){
    int x, y; 

    printf("Please input rows and collumns: \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);              //immediatly 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;
}

2 个答案:

答案 0 :(得分:2)

nul pad the string 然后,读出结果跳过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' 

答案 1 :(得分:0)

你有两个问题

  1. 您需要初始化string变量中的所有字节,而不是使用for循环,您可以在fgets

    之前添加此字节
    memset(string, ' ', x * y);
    

    所以现在字符串中的所有字节都是空格,然后您可以删除尾随'\n'并使用空格更改终止'\0'fgets之后

    size_t length;
    
    length = strlen(string);
    if (string[length - 1] == '\n')
        string[length - 1] = ' ';
    string[length] = ' ';
    
  2. 您需要在'\0'变量中添加终止message,在循环终止后填充message message[k] = '\0';的循环中

    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++;
        }
    }
    message[k] = '\0';
    
相关问题