zoukankan      html  css  js  c++  java
  • scanf_s获取参数,清空缓冲区,判断是否读取成功

    #include<stdio.h>
    
    int main() {
        char str[5];
        while (1) {
            printf("Please input:
    ");
            int rtn=scanf_s("%s", str, 5);
            if (rtn == 0) {
                printf("scanf_s failure!
    ");
                rewind(stdin);//windows平台下清空字符缓冲区。fflush(stdin)不建议使用,好像没有效果
            }
            else {
                printf("Your input:%s
    ", str);
            }
            printf("%d-----------------------------------------------
    ", rtn);
        }
        return 0;
    }

    如果是使用scanf注意内存越界,改变了其他变量的值。注意限制字符读取的长度。

    以下是运行结果:

    Please input:
    123456789
    scanf_s failure!
    0-----------------------------------------------
    Please input:
    1
    Your input:1
    1-----------------------------------------------
    Please input:
    11
    Your input:11
    1-----------------------------------------------
    Please input:
    111
    Your input:111
    1-----------------------------------------------
    Please input:
    1111
    Your input:1111
    1-----------------------------------------------
    Please input:
    11111
    scanf_s failure!
    0-----------------------------------------------
    Please input:
    111111
    scanf_s failure!
    0-----------------------------------------------
    Please input:

     如果清空缓冲区的那一行代码被注释,如下:

    #include<stdio.h>
    
    int main() {
        char str[5];
        while (1) {
            printf("Please input:
    ");
            int rtn=scanf_s("%s", str, 5);
            if (rtn == 0) {
                printf("scanf_s failure!
    ");
                //rewind(stdin);//windows平台下清空字符缓冲区。fflush(stdin)不建议使用,好像没有效果
            }
            else {
                printf("Your input:%s
    ", str);
            }
            printf("%d-----------------------------------------------
    ", rtn);
        }
        return 0;
    }

    则运行结果变成了

    Please input:
    123456789
    scanf_s failure!
    0-----------------------------------------------
    Please input:
    Your input:6789
    1-----------------------------------------------
    Please input:
    111111111111111111
    scanf_s failure!
    0-----------------------------------------------
    Please input:
    scanf_s failure!
    0-----------------------------------------------
    Please input:
    scanf_s failure!
    0-----------------------------------------------
    Please input:
    Your input:111
    1-----------------------------------------------
    Please input:

    最后一定要注意scanf_s的后面的长度虽然是5,但是只能接收4个字符,不然就会接收键盘输入失败。

    另外,scanf_s的第二个参数是变量的地址(数组名也是变量的地址),第三个参数是(unsigned int)的类型(也可以直接使用正整数)

  • 相关阅读:
    c语言的注意事项(未完,以后遇到问题继续添加)
    const与指针的运用
    A7139射频模块wor配置解析
    lora项目注意事项(只用于本项目)
    串口通信数码管显示输入数字
    点阵图形上移
    按键弹起数字增加和按下增加
    数码管从999999倒计时
    中断与数码管秒表显示
    PHP控制连接打印机
  • 原文地址:https://www.cnblogs.com/kgtone/p/9570178.html
Copyright © 2011-2022 走看看