Search code examples
cunixtolower

tolower() function problems


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?


Solution

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