How to correctly input a string in C

前端 未结 5 2084
忘掉有多难
忘掉有多难 2021-01-22 14:38

I am currently learning C, and so I wanted to make a program that asks the user to input a string and to output the number of characters that were entered, the code compiles fin

5条回答
  •  迷失自我
    2021-01-22 15:22

    This line:

    char i[] = "";
    

    is equivalent to:

    char i[1] = {'\0'};
    

    The array i has only one element, the program crashes because of buffer overflow.

    I suggest you using fgets() to replace scanf() like this:

    #include 
    #define MAX_LEN 1024
    
    int main(void)
    {
        char line[MAX_LEN];
        if (fgets(line, sizeof(line), stdin) != NULL)
            printf("%zu\n", strlen(line) - 1);
        return 0;
    }
    

    The length is decremented by 1 because fgets() would store the new line character at the end.

提交回复
热议问题