关于printf,scanf,getchar函数用法的深入分析

1 篇文章 0 订阅
1 篇文章 0 订阅

printf,scanf和getchar都是接触C语言时首先了解的函数之一,但在学习过程中这三个函数有部分功能容易被忽略,在此特做总结。

1.printf函数的返回值

printf函数能够实现各种内容的打印,来自C Library定义为 :

int printf ( const char * format, ... );

On success, the total number of characters written is returned.

If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.

If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned. 

因此printf函数同样具有返回值,在输出成功时返回输出的字符个数,如下例

printf("%d",printf("%d",printf("%d",43);

函数由最内层向外依次输出“43”,“2”和“1”,结果为4321。

2.scanf函数和getchar函数的返回值

scanf函数和getchar函数都能够实现内容的输入,来自C Library定义

scanf函数
int scanf ( const char * format, ... );

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. 

getchar函数
On success, the character read is returned (promoted to an int value).
The return type is int to accommodate for the special value EOF, which indicates failure.

即scanf在读取时会返回读取成功的个数,例如下面代码会返回2

scanf("%d%d",&a,&b);

在没有读取到内容时,scanf会返回EOF(-1)

getchar会返回输入的字符的ASCII码值,在输入失败时同样返回EOF

因此,在处理多组输入类型的题目时,可以用以下代码来进行判断:

while(scanf())//输入判断
{
    Content;//执行命令
}
while((ch=getchar())!=EOF)
{
    Content;
}

3.scanf函数和getchar函数的读取

scanf和getchar都不是从键盘上直接读取内容。在键盘输入后,输入内容将被存入缓冲区,两个函数都会从缓冲区内根据相应的格式读取对应内容。

这里便涉及‘\n’即Enter的读取问题

(1)scanf函数

scanf能够实现各种内容的输入,在读取输入时遇到空格,Enter,Tab即停止本次读取,并将读取内容放入缓冲区(空格,Enter,Tab不会被放入缓冲区)

但也有例外情况,在以%c形式进行scanf输入时,scanf会读取Enter并存放在缓冲区中

(2)getchar函数

getchar只能一个字符一个字符进行读取,读取的数据以ASCII码即int形式返回,Enter,Tab和空格都会进行读取

以经典大小写转换连续输入输出问题为例:

#include<stdio.h>
int main()
{
    char ch = 0;
    while (scanf("%c",&ch))
    {   
        printf("%c\n", ch + 32);
    }
    return 0;
}

 这种情况下,scanf按%c即一个字符一个字符读取,例如输入大写字母A并回车

scanf检测到Enter识别输入结束,先读取大写字母A,再一次循环读取缓冲区内的Enter,因此会输出a,*(Enter对应的ASCII码10+32)两行数据

这种问题有两种解决方法,一种是使用getchar将缓冲区内的Enter取走

    char ch = 0;
    while (scanf("%c",&ch))
    {   
        printf("%c\n", ch + 32);
        getchar();
    }

另一种是将输入格式变为%s,使Enter(\n)不被读取

    char ch = 0;
    while (scanf("%s",&ch))
    {   
        printf("%c\n", ch + 32);
    }

使用getchar解决该问题时,因为getchar函数只会一个一个字符读取,并且一定会读取空格,Enter和Tab,因此不涉及上述scanf函数出现的问题。

    int ch=0;
    while((ch=getchar())!=EOF)
    {
        putchar(ch+32);
        getchar();
        printf("\n");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值