1.printf()2.scanf()

简介: 1.printf()2.scanf()

1.printf()


2.scanf()


1.printf()


printf函数也是有返回值的。


Return Value


Each of these functions returns the number of characters printed, or a negative value if an error occurs.


返回所打印字符的数,如果错误返回负值.


来个小题目:


KiKi写了一个输出“Hello world!”的程序,BoBo老师告诉他printf函数有返回值,你能帮他写个程序输出printf(“Hello world!”)的返回值吗?


读者可以自行做一下:

看作者的表演:

#include <stdio.h>
int main()
{
  printf("\n%d", printf("Hello world!"));
  return 0;
}

小伙伴们,你们作对了吗?

2.scanf()

scanf()库函数为读入函数,从键盘上读入,读入时先储存到一个名为缓冲区的储存区域,遇到'\n'(即键盘上的Enter回车键)停止读入,下面就开始sacnf从缓冲区进行数据的读取,在遇到空格和非打印字符时停止读入,剩下的数据仍在缓冲区中储存着,等待着下一次的读取。


看下面这个题目:


描述

输入一个学生各5科成绩,输出该学生各5科成绩及总分。


输入描述:

一行,输入该学生各5科成绩(浮点数表示,范围0.0~100.0),用空格分隔。


输出描述:

一行,按照输入顺序每行输出一个学生的5科成绩及总分(小数点保留1位),用空格分隔。先看傻傻

一行,按照输入顺序每行输出一个学生的5科成绩及总分(小数点保留1位),用空格分隔。先看傻傻是我是怎么用数组做的:

看下面的代码:

#include <stdio.h>
int main()
{
  float cj[5];
  float sum = 0;
  int n;
  for (n = 0; n < 5; n++)
  {
    scanf("%f", &cj[n]);
    sum += cj[n];
  }
  for (n = 0; n < 5; n++)
  {
    printf("%.1f ", cj[n]);
  }
  printf("%.1f", sum);
  return 0;
}

用我们c语言老师说的话讲:就这你居然用数组做,直接0分。

其实是没有必要的:

#include <stdio.h>
int main()
{
  float cj;
  float sum = 0;
  int n;
  for (n = 0; n < 5; n++)
  {
    scanf("%f", &cj);
    sum += cj;
    printf("%.1f ", cj);
  }
  printf("%.1f", sum);
  return 0;
}

那我为什么还这样做呢?那就是没有明白scanf()函数的用法,一直是想着它只能读入一个。


其次scanf库函数是有返回值的:


下面是我在MSDN上截取的片段:


Return Value


Both scanf and wscanf return the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.


大概是什么意思呢?scanf返回成功读取的项数。如果没有读取任何项,且需要用户读取一个数字而却输入一个非数值字符,则返回0。遇到文件结尾时,返回EOF。


EOF的值是多少呢?我们转到定义:发现是-1

相关文章
|
1月前
|
C语言
你真的学会了printf和scanf函数吗?
你真的学会了printf和scanf函数吗?
|
30天前
|
编译器 C语言 C++
scanf函数
该文介绍了C语言中`scanf`函数用于输入变量值,而`printf`函数用于输出变量值。`scanf`在读取数值时会自动过滤空白字符,允许数据间有空格或换行,不影响解析。`scanf`返回值表示成功读取的变量数,0表示未读取或匹配失败,EOF表示读取错误或文件结尾。常见占位符包括 `%c`(字符)、`%d`(整数)、`%f`(浮点数)、`%s`(字符串)和`%[]`(指定字符集)。对于`%c`,不会忽略空白字符,但可加空格跳过前导空白。文章还提及在VS2022中,`scanf`被认为是不安全的,推荐使用`scanf_s`,并提供了如何在VS中使用`scanf`的解决方法。
26 1
|
10月前
scanf和getchar区别
scanf和getchar区别
135 0
有关printf(p+1),printf(p++),printf(++p)的相关理解
有关printf(p+1),printf(p++),printf(++p)的相关理解
48 0
|
6月前
|
缓存
scanf和printf函数
scanf和printf函数
70 0
|
6月前
c中scanf函数注意点
c中scanf函数注意点
34 0
|
11月前
|
存储 Serverless C语言
printf()和scanf() (详解)
printf()和scanf() (详解)
|
C语言
论Scanf、Gets、Getchar的区别
论Scanf、Gets、Getchar的区别
127 0
当后面有 fgets()/gets()/scanf() 时 scanf() 出现问题
首先让我们来考虑下面用 C 编写的简单程序。该程序使用 scanf() 读取一个整数,然后使用 fgets() 读取一个字符串。
43 0
scanf与scanf_s
scanf与scanf_s
85 0