0

我正在尝试从头开始制作一个 tolower 函数(出于学习目的),即使我转换了正确的类型,也会不断收到此错误:

alternate.c:13:18: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *'; [-Werror]
                                strcat(temp, (char) i + 32);
                                             ^~~~~~~~~~~~~
/usr/include/string.h:136:72: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, __const char *__restrict __src)
                                                                       ^
alternate.c:15:19: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *'; [-Werror]
                                strcat(temp,  i);
                                              ^
/usr/include/string.h:136:72: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, __const char *__restrict __src)
                                                                       ^
alternate.c:18:17: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror]
                        strcat(temp, uppercase[i]);
                                     ^~~~~~~~~~~~
                                     &
/usr/include/string.h:136:72: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, __const char *__restrict __src)
                                                                       ^
3 errors generated.

这是导致麻烦的代码:

char * toLowerCase(char * uppercase){
    char * temp = "";
    for(int i =0; i<strlen(uppercase); i++){

        if( (int) uppercase[i] != 32){

            if( (int) uppercase[i] < 97){
                strcat(temp, (char) i + 32);
            }else{
                strcat(temp,  i);
            }
        }else{
            strcat(temp, uppercase[i]);
        }   
    }
    return temp;
}
4

1 回答 1

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

char *toLowerCase(const char *uppercase){
    char *temp = malloc(strlen(uppercase)+1);

    if(temp){
        char *p = temp;
        while(*p++ = tolower(*uppercase++));
        /*
        while(*uppercase){
            *p++ = tolower(*uppercase++);
        }
        *p = '\0';
        */
    }
    return temp;
}

int main(void){
    char *str = toLowerCase("ABC-XYZ");
    printf("%s\n", str);//abc-xyz
    free(str);
    return 0;
}
于 2013-08-03T20:32:42.680 回答