Home > Backend Development > C++ > body text

Usage of scanf_s in c language

下次还敢
Release: 2024-04-30 00:33:17
Original
404 people have browsed it

scanf_s is a safe function in C language to read formatted data to prevent buffer overflow attacks. Its syntax is: scanf_s(format, ...). Usage steps: Include the header file stdio.h. Prepend the & symbol before the variable. Make sure the format specifier matches the data type. Check the return value to detect errors.

Usage of scanf_s in c language

Usage of scanf_s in C language

The scanf_s function is used in C language to read format from standard input A secure version of your data. Unlike the unsafe scanf function, scanf_s validates input and protects against buffer overflow attacks.

Syntax

<code class="c">int scanf_s(const char *format, ...);</code>
Copy after login

Parameters

  • format: A format specifier string , specifying the data type to be read.
  • ...: A variable argument list providing the address of the data to be read.

Return value

scanf_s Returns the number of items that have been successfully read. Returns -1 if the input is malformed or an error is encountered.

Usage

To use scanf_s, follow these steps:

  1. Include the stdio.h header file .
  2. Place the & symbol before the variable from which data is to be read.
  3. Make sure the format specifier matches the data type being read.
  4. Check the return value of scanf_s to detect errors.

Example

<code class="c">#include <stdio.h>

int main()
{
    int age;
    char name[20];

    printf("输入你的年龄:");
    if (scanf_s("%d", &age) != 1)
    {
        printf("输入无效!\n");
        return 1;
    }

    printf("输入你的姓名:");
    if (scanf_s("%s", name, sizeof(name)) != 1)
    {
        printf("输入无效!\n");
        return 1;
    }

    printf("你好,%s!你的年龄是 %d。\n", name, age);

    return 0;
}</code>
Copy after login

Notes

  • scanf_s is a safe version and scanf will not appear Buffer overflow problem in .
  • scanf_s returns the number of items successfully read, not the number of matching items like scanf.
  • To scan a string, use the %s format specifier and specify the maximum length of the string.
  • scanf_s does not support the %n format specifier.

The above is the detailed content of Usage of scanf_s in c language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!