-1

接受用户输入时,有时会收到未知字符:

http://imageshack.us/photo/my-images/833/capture1ec.jpg/

这是我的代码:

#include <stdio.h>

void main()
{
    char plaintext[50];
    char arr[10]={'a','b','c','d','e','f','g','h','i','j'};
    char key[20];
    int plain=0,max1=0,max2=0;
    char chip[30][30];
    int z=0,i,j,k=0,c=0,a;
    char swap,temp; 
    printf("Enter key :");
    scanf("%[^\n]",key);

    for(i=0;key[i]!='\0';i++)
    {
        max2++; 
    }

    printf("Enter plaintext :");
    scanf("%s",&plaintext);

    for( i = 0; plaintext[i] != '\0'; i++ ) 
    {
        plain++; 
    }

    if (plain%max2==0)
        max1=plain/max2;
    else
        max1=plain/max2+1;

    while (plaintext[k]!='\0')
    {        
        for (i=0;i<max1;i++)
        {
            for (j=0;j<max2;j++)
            {
                if (plaintext[k]!=NULL)
                {
                    chip[i][j]=plaintext[k];
                    k++;
                }
            }
        }
    }

    /*printf("\n");
    for (i=0;i<max1;i++)
    {
        for (j=0;j<max2;j++)
        {
            printf("%c ",chip[i][j]);
        }
        printf("\n");
    }*/

    for(i=0;i<max2;i++)
    {
        if(chip[max1-1][i]==NULL)
        {
            chip[max1-1][i]=arr[c];
            c++;
        }
    }

    printf("\n");
    /*for (i=0;i<max1;i++)
    {
        for (j=0;j<max2;j++)
        {
            printf("%c ",chip[i][j]);
        }
        printf("\n");
    }*/

    for (i = 0 ; i < max2; i++)
    {
        for (j = 0 ; j < max2 ; j++)
        {
            if (key[i] < key[j]) 
            {
                swap = key[j];
                key[j] = key[i];
                key[i] = swap;

                for (a=0;a<max1;a++)
                {
                    temp=chip[a][j];
                    chip[a][j]=chip[a][i];
                    chip[a][i]=temp;
                }
            }
        }
    }

    /*printf("\n");
    for (i=0;i<max1;i++)
    {
        for (j=0;j<max2;j++)
        {
            printf("%c ",chip[i][j]);
        }
        printf("\n");
    }*/
    for (i=0;i<max2;i++)
    {
        for (j=0;j<max1;j++)
        {
            if (chip[j][i]!=NULL)
                printf("%c ",chip[j][i]);
        }
    }
}
4

1 回答 1

0

在使用之前尝试添加它chip

#include <string.h>

...

char chip[30][30];
memset(chip, 0, 30 * 30);  // <- add this one

...

或者干脆

char chip[30][30] = {0};
于 2013-04-02T03:57:49.137 回答