How to set a string for all lowercase

I have a char foo[SIZE]; //(string) char foo[SIZE]; //(string)

and enter it correctly using %s (as printfs correct input in it), but now you want to set it to lowercase. So I tried to use

  if (isupper(*foo)) *foo=tolower(*foo); 

those. when i do:

 printf("%s" foo); //I get the same text with upper case 

The text does not seem to change. Thanks.

+4
source share
3 answers

foo not a pointer, so you do not want to use it as one. You also do not need to check if the character is an uppercase letter before using tolower - it converts upper and lower case and leaves other characters unchanged. You probably want something like:

 for (i=0; foo[i]; i++) foo[i] = tolower((unsigned char)foo[i]); 

Note that when you call tolower (and toupper , isalpha , etc.), you really need to make your input unsigned char . Otherwise, many (most?) Characters outside the main English / ASCII character set will often lead to undefined behavior (for example, in the typical case, the most accented characters will appear as negative numbers).

Aside, when you read a line, you do not want to use scanf with %s - you always want to specify the length of the line, for example: scanf("%19s", foo); assuming SIZE == 20 (i.e. you want to specify one size smaller. Alternatively, you can use fgets , for example fgets(foo, 20, infile); Note that with fgets you specify the size of the buffer, not one less you do with scanf (and a company like fscanf).

+4
source

try it

 for(i = 0; foo[i]; i++){ foo[i] = tolower(foo[i]); } 
+2
source

*foo=tolower(*foo); //doing *(foo+i) or foo[i] does not work either

because all these parameters do not make sense

You should use it as follows:

 for(i = 0; foo[i] != '\0'; i++){ foo[i] = tolower(foo[i]); } 
+2
source

Source: https://habr.com/ru/post/1484325/


All Articles