use*_*044 5 c lowercase uppercase toupper tolower
我有一个 char foo[SIZE]; //(string)
并使用正确输入%s(如printfs正确输入),但现在要将其设置为小写。所以我尝试使用
if (isupper(*foo))
*foo=tolower(*foo);
Run Code Online (Sandbox Code Playgroud)
即当我这样做:
printf("%s" foo); //I get the same text with upper case
Run Code Online (Sandbox Code Playgroud)
文字似乎没有改变。谢谢。
foo不是指针,因此您不想将其用作指针。您也不必在使用前检查字符是否为大写字母tolower-它将大写转换为小写,并使其他字符保持不变。您可能想要类似的东西:
for (i=0; foo[i]; i++)
foo[i] = tolower((unsigned char)foo[i]);
Run Code Online (Sandbox Code Playgroud)
请注意,当您调用tolower(和toupper,isalpha等)时,确实需要将输入投射到unsigned char。否则,基本英语/ ASCII字符集之外的许多(大多数?)字符将经常导致未定义的行为(例如,在典型情况下,大多数带重音符号的字符将显示为负数)。
顺便说一句,当您阅读字符串时,您不想scanf与%s- 一起使用,您总是想指定字符串的长度,例如:scanf("%19s", foo);,假设SIZE== 20(即,您要指定小于大小。或者,你可以使用fgets,如fgets(foo, 20, infile);需要注意的是与fgets你指定缓冲区的大小,一个都不能少喜欢你做scanf(与公司类似的fscanf)。