giozh
giozh

Reputation: 10068

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?

Upvotes: 1

Views: 9587

Answers (3)

user4815162342
user4815162342

Reputation: 155216

As others mentioned, you need to null-terminate the target string. Aside from that, note that you are recalculating the length of a at each iteration of the loop. This will not matter for small strings, but with large strings you will notice that the time to convert is proportional to the square of the string length. The standard idiom is to calculate the length once and use it repeatedly. With those two changes, the function would look like this:

void convert(const char *a, char *b) {
    size_t i, len = strlen(a);
    for(i = 0; i < len; i++) {
        b[i] = tolower((unsigned char) a[i]);
    }
    b[len] = '\0';
}

Upvotes: 2

gil_bz
gil_bz

Reputation: 484

strlen returns the length of the string, for instance strlen("hello") is 5. This does not copy the 0 character used to terminate the string (which means the string in the memory is actually 6 characters long: 'h' 'e' 'l' 'l' 'o' '0')

Upvotes: 1

md5
md5

Reputation: 23717

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

Upvotes: 5

Related Questions