how to change single char in string array?

后端 未结 1 1181
耶瑟儿~
耶瑟儿~ 2021-01-27 01:36

Having this:

#include 
#include 
#include 

char *up(char *);

int main() {
    char initstr[20];
    printf(\"ente         


        
1条回答
  •  醉梦人生
    2021-01-27 02:33

    The bug in up is you increment ret all the way to the newline (\n) and return ret pointing to this character in the string. You should instead return a pointer to the initial character.

    • It is simpler to write this function using an index.
    • packing all the logic into the for clauses with an empty body is hard to read and error prone.
    • Note also that the string might not contain a newline, so it is safer to stop at the null terminator, the newline will not be changed by toupper().
    • Finally, you should not pass char values to toupper() because this function and all functions from is only defined for values of type unsigned char and the special negative value EOF. On platforms where char is signed by default, the string might contain negative char values which may cause undefined behavior when passed to toupper(). Cast these as (unsigned char) to avoid this issue.

    Here is a modified version:

    #include 
    #include 
    
    char *up(char *s) {
        for (size_t i = 0; s[i] != '\0'; i++) {
             s[i] = toupper((unsigned char)s[i]);
        }
        return s;
    }
    
    int main() {
        char initstr[20];
        printf("enter string\n");
        if (fgets(initstr, sizeof initstr, stdin)) {
            char *str = up(initstr);
            printf("%s\n", str);
        }
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题