• fgets读入一行字符串测试注意点


    安全的用法是:如果你一行至多有x个字符要读入,就用char s[x + 2];fgets(s, x + 2, stdin);这样保证读入的字符串不会被截断(截断是很危险的,不仅影响这一次的读入,还会影响后续的fgets的执行),如果输入K个字符,则s[0..K-1]是输入的字符串,s[K]='\n',s[K+1]='\0',调用printf("%s", s);将打印这一行所有的字符,外加一个换行符

    如果有类似scanf("%d", &n);后面紧跟着fgets(s, x + 2, stdin);——这个fgets将不会要求用户输入,而是直接读如输入缓冲区残留的'\n'

    如果有耐心,可以读读下面的注释,也可以自己用gdb调试,测试各种情况

    #include <stdio.h>
    int main()
    {
        char s[4];
        int n;
        //scanf("%d", &n);
        //fgets(s, 4, stdin);
        //
        //--in this case, you only need to input a number, s[0] = '\n', s[1] = '\0'
    
        //scanf("%d\n", &n);
        //fgets(s, 4, stdin);
        //
        //--in this case, you need to input 2 lines, a number, a string
        //if you input:
        //2
        //ab
        //s will be "ab\n"--s[3] = '\0'
    
        //if you input:
        //2
        //abc
        //s will be "abc"--s[3] = '\0'
    
        //if you input:
        //2
        //abcd
        //s will be "abc"--s[3] = '\0'
        
        //so, how to deal with that?
        //if there are at most x chars, you can use fgets(s, x + 2, stdin)
        //this will ensure there is '\n' and '\0'
    
        fgets(s,4,stdin);
        fgets(s,4,stdin);
        //if you input:
        //ab
        //--it will prompt you to enter another string
    
        //if you input:
        //abc
        //--you don't have the chance to input another string,
        //the later fgets will read remaining bytes from input buffer
        //so, the final s will be "\n",s[0]='\n',s[1]='\0',s[2]='c',s[3]='\0'
        
        //if you input:
        //abcd
        //finally you get s = "d\n",s[0]='d',s[1]='\n',s[2]='\0',s[3]='\0'
        return 0;
    }
  • 相关阅读:
    前端实现文件下载
    es6 Promise简单介绍
    es6开发环境搭建,babel 将es6转化成es5
    如何让写得html页面自动刷新
    es6箭头函数
    js对象跟数组多层嵌套,检测没有此数据就添加有则不添加以及超过限制条件删除操作
    小程序分享进入H5动态网页
    数据结构与算法--基本概念
    Unity中的常用输入
    Unity中的物体旋转
  • 原文地址:https://www.cnblogs.com/fstang/p/2793550.html
Copyright © 2020-2023  润新知