zoukankan      html  css  js  c++  java
  • 用好printf和scanf

    转载自:http://hi.baidu.com/wuxicn/item/f648fe1970f86917e3f98682


    在C中,printf系列函数(fprintf, sprintf...)和scanf(fscanf, sscanf...)函数功能很强大,用好了的话,很多字符操作都可以很简单,甚至一些简单的正则匹配的工作也可以用scanf来完成,下面是几个例子。

    1. printf:

    a) 前导“0”:printf("%05d", n); // n=10, print: "00010"

    b) 左对齐:printf("%-5d|%5d", n, n); // print: "10   |   10"

    c) 自动类型前缀:printf("%#x", n); // print: "0xa"

    d) 指定宽度:printf("%*d", w, n); // w=5, print: "   10"
                      printf("%*.*lf", 5, 1, f); // f=123.45, print: "123.5"

    e) 取得输出长度: printf("%d%n", n, &len); // print: "10" and len=2, %n must be at the end of the formatting string

    2. scanf:

    // s="Used with 12,4.5|0x123 specifiers_the value.";

    a) 基本用法:sscanf(s, "%s %s %d,%f|%x", s1, s2, &a, &f, &b); // s1="Used"; s2="with"; a=12; f=4.5; b=0x123

    b) 跳过一些结果:sscanf(s, "%*s %s", s1); // %*s reads "Used" and ignores it. s1="with"

    c) 限定长度:sscanf(s, "%10s", buf); // read at most 10 chars into buf.

    d) 简单的正则匹配:sscanf(s, "%[a-z]", buf); // buf="with" not "Used"!
                        sscanf(s, "%3c", buf); // buf="Use"

    e) 读入一整行: sscanf(s, "%[^ ]", buf); // buf="Used with 12,4.5|0x123 specifiers_the"



  • 相关阅读:
    ssh环境的搭建,基于注解和配置文件使用
    myeclipse db browser 新建数据源
    区别jquery对象和dom对象及转换方法
    C++中map容器的说明和使用技巧
    csh shell 语法 例子
    如何选择显示器
    Vim简明教程【CoolShell】
    perl
    perlretut
    ssh 配置详解
  • 原文地址:https://www.cnblogs.com/ycpanda/p/3637166.html
Copyright © 2011-2022 走看看