How to correctly input a string in C

前端 未结 5 2127
忘掉有多难
忘掉有多难 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:33

    That's because char i[] = ""; is actually an one element array.

    Strings in C are stored as the text which ends with \0 (char of value 0). You should use bigger buffer as others said, for example:

    char i[100];
    scanf("%s", i);
    

    Then, when calculating length of this string you need to search for the \0 char.

    int length = 0;
    while (i[length] != '\0')
    {
        length++;
    }
    

    After running this code length contains length of the specified input.

提交回复
热议问题