简体   繁体   English

初学者的scanf_s()残疾

[英]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. 我知道scanf_s()有点奇怪,但我无法解决问题。 My code works well by using scanf() but this does NOT reverse the elements of the array :( Any help will be strongly appreciated. Thanks. 我的代码通过使用scanf()可以很好地工作,但这不会反转数组的元素:(任何帮助将不胜感激。谢谢。

scanf_s requires the buffer size in chars to be passed as the second parameter. scanf_s要求将以char为单位的缓冲区大小作为第二个参数传递。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM