Home > Article > Backend Development > Usage of scanf_s in c language
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
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>
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:
stdio.h
header file . &
symbol before the variable from which data is to be read. 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>
Notes
%s
format specifier and specify the maximum length of the string. %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!