有关于scanf还有printf的一些用法及个人发现的一些问题

  首先来讲讲printf把,由于其是比较简单故此先介绍了。

printf函数意思是格式化输出,详细来讲,printf一般是将你想打印的东西通过你输入的格式来转化,而且他的严格性不是很强的,意思是你有时候可以强制类型转换,编译器也不会出想出错信息,或是警告。(在这里稍微提一下scanf,如果在它这里强制类型转换的话,那么编译器就会出现错误的信息)

现在讲讲对于printf返回值,

一般printf返回其打印的个数,如果出错的话,其返回值是负值;


现在讲讲关于scanf语句的一些作用;

scanf函数是格式化输入,其输入格式是非常严格的,当你想把你要输的内容转化为你想要的格式时,你需要非常明白你输入内容的格式,打个比方:当你声明你的输入内容是int类型的时候,你的输入的格式必须是%d,即便你输入的是%d,在你输入内容时,你的输入只能是阿拉伯数字,应为他是int类型,即整型。(千万记住)

 当你想把自己输入的类型转化为char类型时,那么是可以输入任何在ascill码中内的任何字符,应为char为字符型。

最后讲一个最重要的知识点,同时也是我们最容易错误的——————当我们想把我们的内型转化为int类型或是char类型时,我们可以在输入的时候能输出很多字符,当时当我们输入回车时,scanf一般以第一个字符作为判断,如果扫描是碰到某些输入无法于格式控制说明匹配的情况下,该函数将终止执行,同时成功匹配的并赋值的输入项的个数作为函数的返回值。  代码如下:

#include <stdio.h>
#define max 100
main(){
 int p;
 char c;
 char s[max];
 printf("please input:\n");
 scanf("%d %c %s",&p,&c,s);
 printf("the result is :\n");
 printf("%d %c %s\n",p,c,s);
}

一些结果如下:

please input:
abcd abcd abcd
the result is :
0  

please input:
a b c d
the result is :
0  

please input:
5 d abcd
the result is :
5 d abcd

please input:
5 abcd abcd
the result is :
5 a bcd

有关我对最后一个输入的调试:

please input:
5 abcd abcd
the result is :

Breakpoint 1, main () at experience.c:10
10	 printf("%d %c %s\n",p,c,s);
(gdb) p p
$1 = 5
(gdb) p c
$2 = 97 'a'
(gdb) p s[0]
$3 = 98 'b'
(gdb) p s[1]
$4 = 99 'c'
(gdb) p s[2]
$5 = 100 'd'
(gdb) p s[3]
$6 = 0 '\000'

please input:
5dcba abcd abcd
the result is :

Breakpoint 2, main () at experience.c:10
10	 printf("%d %c %s\n",p,c,s);
(gdb) p p
$11 = 5
(gdb) p c
$12 = 100 'd'
(gdb) p s[0]
$13 = 99 'c'
(gdb) n
5 d cba
11	}
(gdb) r
Starting program: /root/lzm/experience 
please input:
5abcd bcde defc
the result is :

Breakpoint 2, main () at experience.c:10
10	 printf("%d %c %s\n",p,c,s);
(gdb) p p
$14 = 5
(gdb) p c
$15 = 97 'a'
(gdb) p [3]
A syntax error in expression, near `[3]'.
(gdb) p s[3]
$16 = 0 '\000'


从中我们可以看到我们即使使用了空格,但是scanf并不是以空格为标准进行输入的,他通过你输入的字符进行判断,而且以空格作为输入的结束,后面的全部没用,这说明了空格在数组中是作为数组的结束标志,在今后我们一点要注意了。

再看一下另一种代码(刚刚想到的觉得有意思):

#include <stdio.h>
#define max 100
main(){
 int s[max];
 char a[max];
 printf("please input:\n");
 scanf("%s %s",a,s);
 printf("the result is :\n");
 printf("%s %s\n",a,s);
}

experience.c: In function ‘main’:
experience.c:7: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int *’
experience.c:9: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int *’

以下是一些输入及其结果:

please input:
abcd123 a23abcd
the result is :
abcd123 a23abcd

please input:
abcd 1234
the result is :
abcd 1234

please input:
1234 abcd
the result is :
1234 abcd

通过这样我们可以的出这样的一个结论:空格一定是作为数组的结束夫,在看一个更有意义的代码:

please input:
a 1234 abcd 1234
the result is :
a 1234

这就是证明。

通过这些,希望读者能够有所借鉴把!



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值