tolower() function problems

giozh picture giozh · Sep 9, 2012 · Viewed 9.5k times · Source

this is my example code:

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

void convert(char *a, char *b) {
    int i;
    for(i=0; i<strlen(a); i++) {
        b[i]=tolower(a[i]);
    }
}

int main() {
    char a[20], b[20];

    fgets(a, sizeof(a), stdin);
    convert(a, b);
    printf("%s\n", b);
    return 0;
}

but sometimes the convert() function convert also one more char than strlen(a) (it's a random char), for example this is an output:

ASDSA
asdsa
%

How can i fix it?

Answer

md5 picture md5 · Sep 9, 2012

You have to add a nul character ('\0') at the end of b.