为什么printf函数不工作

img

img


在线编译这个程序,printf函数正常工作,但是在vs里输入了字符串就没反应了

因为scanf_s()为了防止内存越界,当指定缓存没有足够空间存放输入数据时,scanf_s()直接返回,输入数据没有拷贝到指定缓存。

在你的程序里s数组大小是6,最多只能存储5个字符和'\0',而你却输入了6个字符,s没有足够的空间来存储你输入的字符串,因此scanf_s()直接返回,s数组里的内存没有被修改。

scanf()没有这个问题,因为scanf()不检查数组边界,也因此不安全,容易内存溢出越界。

https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?view=msvc-170

The buffer size includes the terminal null. You can use a width specification field to ensure the token that's read in fits into the buffer. When a token is too large to fit, nothing is written to the buffer unless there's a width specification.

#include <stdio.h>

int main()
{
    char s[6] = "";
    if (scanf_s("%s", s, 6) != 1)
    {
        perror("failed to read a string with max 5 chars");
        return 1;
    }
    printf("%s\n", s);
    return 0;
}
C:> cl main.cpp
C:> main.exe
123456
failed to read a string with max 5 chars: Not enough space
C:> main.exe
12345
12345

数组大小就6个,你实际输入6个字符,用%s是不行的。因为字符串必须有一个字符用来存储字符串结束符。
将数组改为char s[7];scanf("%s",s,7);

你把scanf_s() 的返回值打印一下呢,你看看函数出错了没有