cscanfc11crttr24731

A Beginner's scanf_s() Disability


int main(void) {
    char tmp, arr[100];
    int i, k;

    printf("Enter a string: ");
    scanf_s("%s", arr);

    for ( k = 0, i = (strlen(arr) - 1); k < (int) (strlen(arr) / 2); --i, ++k) {
            tmp = arr[k];
            arr[k] = arr[i];
            arr[i] = tmp;
    }

    puts(arr);

    return 0;
}

I know that there is something weird about scanf_s() but I could NOT resolve the issue. My code works well by using scanf() but this does NOT reverse the elements of the array :( Any help will be strongly appreciated. Thanks.


Solution

  • scanf_s requires the buffer size in chars to be passed as the second parameter.

    int iNumFilled1 = scanf_s("%s", arr);
    int iNumFilled2 = scanf_s("%s", arr, _countof(arr));
    assert(iNumFilled1 == 0);
    assert(iNumFilled2 == 1);
    

    You can also pass a width specifier. If passed and it does not fit into the buffer you will have only the first 'width specified' chars.

    //Input a string longer than 99 chars
    int iNumFilled3 = _tscanf_s(_T("%99s"), arr, _countof(arr));
    assert(iNumFilled3 == 1);
    
    //Again insert a string longer than 99 chars, but with no width specifier
    int iNumFilled4 = _tscanf_s(_T("%s"), arr, _countof(arr));
    assert(iNumFilled4 == 0);