C语言 scanf

C语言 scanf 函数

scanf 主要通过键盘获取输入字符

scanf通过%转义的方式可以得到用户通过标准输入设备输入的数据。

使用案例

// 关闭scanf警告方法1:必须在文件第一行
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
// 关闭scanf警告方法2:可放到任意一行
#pragma warning(disable:4996)

int main(void)
{
    // 通过键盘输入赋值
    int a;
    
    // &运算符、表示取地址运算符
    scanf("%d", &a);
    printf("%d
", a);
    return 0;
}
scanf 使用案例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    // 打印一个字符
    char ch;
    scanf("%c", &ch);
    putchar(ch);

    // 打印多个字符、每个变量分隔可通过、空格 或 回车 来分隔。
 // scanf 中不能加入/n。
 // %3d 表示约束整形数为三位数字 
    int a, b;
    scanf("%3d %d", &a, &b);
    printf("%d	%d", a, b);
    return EXIT_SUCCESS;
}
scanf 使用案例:2
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    // "%9s":用户输入字符串值约束
    // "%[^
]":输入可以带空格
    char cxx[5];
    scanf("%9s", cxx);

    return 0;
}
scanf 使用案例:输入可以带空格

扩展

1、gets(str)与scanf(“%s”,str)的区别:

  • gets(str)允许输入的字符串含有空格
  • scanf(“%s”,str)不允许含有空格

2、注意:由于scanf()和gets()无法知道字符串s大小,必须遇到换行符或读到文件结尾为止才接收输入,因此容易导致字符数组越界(缓冲区溢出)的情况。

原文地址:https://www.cnblogs.com/xiangsikai/p/12372613.html