数据的输入、输出

数据的输入输出

  • 字符输出函数

    int putchar(int c) : 功能:在标准输出上面显示一个字符

  • 格式化输出函数

    int printf(const char *format…) : 功能:格式化字符串输出

    常用的格式:

    格式符作用
    i,d十进制整数
    x,X十六进制无符号整数
    o八进制无符号整数
    %%百分号本身
    s字符串
    f小数形式浮点数
    e,E指数形式浮点数

    一个格式说明可以带0个或者多个修饰符,用来指定显示宽度、小数尾数及左对齐等。

    修饰符功能
    m输出数据域宽,数据长度<m,左补空格;否则按实际输出
    .n对实数指定小数点后位数;对字符串指定实际输出位数
    -输出数据在域内左对齐(缺省为右对齐)
    +指定在有符号数的整数面前显示+号
    0输出数值时指定左面不使用的空格位置自动填0
    #在八进制和十六进制数前显示前导0,0x

    常用转义字符:

    转义符功能
    \b退格,将当前位置移到前一列
    \n换行,将当前位置移到下一列开头
    \t水平制表(跳到下一个TAB位置)
    \\代表一个反斜杠字符
  • 数据的输入

    int getchar(void) : 成功返回读到的字符,失败或读到结束符返回EOF(-1)。

  • 格式化输入函数

    int scanf(const char *format…) : format指定输入格式,后面跟要输入的变量的地址,为不定参。

    字符含义
    i,d十进制数
    x,X十六进制无符号整数
    o八进制无符号整数
    c单一字符
    s字符串
    f小数形式浮点数

    修饰符

    修饰符功能
    h用于d,o,x前,指定输入为shortzing整数
    l用于d,x,o前,指定输入为long型整数;用于e,f前指定输入为double型
    m指定输入数据的宽度
    *抑制符,指定输入项读入后不赋值给变量
    • 用"%c"格式符时,空格和转义字符作为有效字符输入。(注意:此时会有一个问题,就是当输入一个字符后按回车键结束,回车键会被留在缓存中,此时需要跟一个getchar()将该字符读走,下边有例子)。

    • 输入数据时,遇到以下情况认为该数据结束;

      • 空格、TAB、或回车
      • 宽度结束
      • 非法输入
    • scanf函数返回值是成功输入的变量的个数,当遇到非法输入时,返回值小于实际变量个数。

    • 使用输入函数可能会留下垃圾(会将换行或空格读入),解决办法:

      • 调用getchar函数,清除垃圾字符

      • 用格式串中空格或者"%*c"来"吃掉"。如:

        int main()
        {
            int a;
            char ch;
            printf("input a number:");
            scanf("%d",&a);
            printf("a=%d\n",a);
        
        <span class="token comment">//getchar();	读走垃圾</span>
        
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"input a charactor:"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">scanf</span><span class="token punctuation">(</span><span class="token string">"%*c%c"</span><span class="token punctuation">,</span><span class="token operator">&amp;</span>ch<span class="token punctuation">)</span><span class="token punctuation">;</span>	<span class="token comment">//读走缓存中的垃圾</span>
        <span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"ch=%c %d\n"</span><span class="token punctuation">,</span>ch<span class="token punctuation">,</span>ch<span class="token punctuation">)</span><span class="token punctuation">;</span>
        

}
字符串输入输出函数

  • 字符串输出函数puts

    int puts(const char *s); //s为要输出的字符串

  • 字符串输入函数gets

    char *gets(char *s);

    从键盘输入一回车结束的字符串放入数组中并自动就加’\0’,在使用该函数的时候要注意数组越界的问题(因为gets不会检查长度,当输入的数据超过数组的长度的时候就会发生越界问题,所以在使用该函数时,需要注意字符的长度)。

    注意:gets函数并不以空格作为字符串输入结束标志,而质疑回车作为输入结束,这与scanf是不同的

posted @ 2022-11-21 18:54  TwcatL_tree  阅读(0)  评论(0编辑  收藏  举报