How to use tolower() with char*?

PoorProgrammer picture PoorProgrammer · Dec 14, 2016 · Viewed 10k times · Source

I have a .txt file with some words and I need them to be lowercase. How to make each word lowercase? Just adding tolower() to strtok() doesn't work. What should I add? Or maybe it would be easier to use tolower() on whole file firstly? But how? Please help!

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

int main(void)
{
    char str[5000];
    char *ptr;
    char *words[5000];
    FILE * fp = fopen("hi.txt", "r");
    fgets(str, 49, fp);             
    ptr = strtok(str, ",.; ");         
    int i = 0;
    while(ptr != NULL)  
    {
        words[i]= ptr;
        i++;
        ptr = strtok(NULL, ",.; "); 
    }
    fclose(fp);

    for(int j=0;j<i;j++) {
        printf("%s\n", words[j]);
        //printf("%s\n", tolower(words[j])); // Doesn't work!
    }
    return 0;
}

Example:

hi.txt

Foo;
Bar.
Baz.

Expected output

foo
bar
baz

Answer

sameera sy picture sameera sy · Dec 14, 2016

tolower() works only for single characters. You can make use of the below function to convert strings to lower case:

printf("%s\n", cnvtolwr(mystring));

The implementation of the function is as below.

char *cnvtolwr(char *str)
{
    unsigned char *mystr = (unsigned char *)str;

    while (*mystr) {
        *mystr = tolower(*mystr);
        mystr++;
    }
    return str;
}