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
The
tolowerfunction takes a single character and makes it lower case, so calling it on achar*doesn't really make sense. If you know that only the first character of each substring returned bystrtokis upper case, you need to calltoloweron that character specifically within your loop. In other words, something like this:If there are more characters in the string that could be upper case and you want to make sure that they become lower case, you need to iterate through the substring and call
toloweron every character: