Bernardo Meurer
Bernardo Meurer

Reputation: 2355

printf not printing last character

I'm making a simple code for simulating Caesar's cypher and I'm having a weird bug where, although the output string fraseout[] is formed correctly and will print correctly at the very last print it gets it's last character trimmed. Why is this happening?

#include <stdio.h>
#include <string.h>
#include <math.h>
int main (void)
{
        printf("Insira a frase:\n");
        char frase [256];
        scanf("%s", frase);
        int size = (int)strlen(frase);
        printf("Insira o tamanho da divergência: \n");
        int diff = 0;
        scanf("%i", &diff);
        char fraseout [size];
        int i = 0;
        for (i = 0; i<=size-1; i++)
        {
                int val = (int)frase[i];
                if (val + diff > 126)
                {
                        val = 31+diff-(126-val);
                }
                else if (val +diff < 32)
                {
                        val = 127 + diff+(val-32);
                }
                else
                {
                        val +=diff;
                }
                fraseout [i] = (char)val;
        }

        printf("\"%s\" -> \"%s\"\n", frase, fraseout);
        return 0;
}

Upvotes: 2

Views: 1447

Answers (2)

dbush
dbush

Reputation: 225637

fraseout is not long enough to hold the NULL terminating byte, so you need to make it one bigger:

char fraseout [size+1];

Also, after building fraseout, you need to make sure it's NULL terminated, otherwise you'll print garbage:

fraseout[size] = '\0';

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

There are two related points,

  1. Need to take the size as strlen()+ 1, as strlen() does not take into account the terminating null.
  2. Need to make the fraseout[i], the last element as 0 or '\0' to make it usable as a string.

Upvotes: 1

Related Questions