help codification zenith polar in c

0

I made a program in codeblocks which should code in polar zenith and although it identifies the characters and exchanges it generates a problem with the characters that are not exchanged transforming them into completely different characters

    void f()
    {
        int i,p;
        char n[30],c[30];

        char g[]="cenit";
        char k[]="polar";

        printf("cenit\n");
        fgets(n,30,stdin);
        printf("%s",n);

        for(i=0;i<30;i++)
        {
            for(p=0;p<6;p++)
            {
                if(n[i]==g[p])
                {
                    c[i]=k[p];
                }

                if(n[i]==k[p])
                {
                    c[i]=g[p];
                }
            }
        }

        printf("%s\n",c);
    }
    
asked by Rohan 02.11.2017 в 02:10
source

1 answer

1

If your code is throwing strange codes, it is because the array you use coo exit ( c[30] ) is not initializing it. That is why it keeps "junk" values. To initialize said arrangement you have some alternatives. The most common will be to use a cycle for like the following:

for(i = 0; i < sizeof(c); i++)
{
    c[i] = '
char g[]="cenit"
'; }

This will cause the array to be initialized with string termination characters.

Recall that in C, the end of a string is identified through the chain termination character '%code%' . For example, the string you have defined in the following line:

{'c', 'e', 'n', 'i', 't', '
            if(n[i]==g[p])
            {
                c[i]=k[p];
            }

            else if(n[i]==k[p])
            {
                c[i]=g[p];
            }
'}

It will be composed of the characters:

for(i = 0; i < sizeof(c); i++)
{
    c[i] = '
char g[]="cenit"
'; }

That's why its size is 6

The rest of your logic looks good but for clarity I would use a else-if

{'c', 'e', 'n', 'i', 't', '
            if(n[i]==g[p])
            {
                c[i]=k[p];
            }

            else if(n[i]==k[p])
            {
                c[i]=g[p];
            }
'}
    
answered by 02.11.2017 в 06:05