• 关于c语言的输入输出


    1.scanf函数

      最常用的输入函数算是scanf函数了,要注意的就是它遇到空格、tab和回车就会停止读取,并且空格、tab和回车符仍存在于缓冲区中,如果下一个读取的是字符的话就得注意了。

    2.fgets函数

      作用:读取完整的一行数据

      用法:char buf[MAXN];

          fgets(buf, MAXN, fin);

      说明:这个函数一旦读到回车符'\n'就会停止读取,并把'\n'读到字符串中。此外,该函数只读取不超过MAXN-1个字符,然后再末尾添上结束符'\0',因此不会出现越界的情况。

      实例:

    View Code
     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 int main(void)
     5 {
     6     char s[200];
     7     int len, i;
     8     while(fgets(s, 200, stdin))
     9     {
    10         len = strlen(s);
    11         printf("length: %d\n", len);
    12         for(i = 0; i < len; i++)
    13             printf("%d ", s[i]);
    14         printf("\n");
    15     }
    16 }

      上面的程序第一行只输入了一个回车,字符长度为1,保存的是'\n'字符(ASCII码为10),第二个数据为hello,长度为6,使用这个函数时取有效字符串长度时记得减1。

    3.gets函数

      作用: 读取完整的一行数据

      实例:

    View Code
     1 #include <cstdio>
     2 #include <cstring>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     char s[100];
     8     while(gets(s))
     9     {
    10         int len = strlen(s);
    11         printf("length: %d\n", len);
    12         for(int i = 0; i < len; i++)
    13             printf("%d ", s[i]);
    14         printf("\n");
    15         printf("%s\n", s);
    16     }
    17     return 0;
    18 }

      说明: gets函数遇到回车符'\n'停止读取,与fgets不同的是,gets函数并不把'\n'字符写进字符数组内,所以字符数组内保存的是实际长度。但是,由于gets函数存在缓冲区溢出漏洞,并不被推荐使用。

    4.fgetc函数

      作用: 读取一个打开的文件fin, 读取一个字符

      用法: fgetc(fin)

      说明: fgetc函数返回一个int值,这是因为当文件结束是,fgetc将返回EOF,值为-1,无法赋值给char类型的数据。另外, fgetc(stdin)等价于getchar()。

    5.printf函数

      关于printf("%6.2f\n", a); 中小数点是否占位的问题。

    View Code
    1 #include <stdio.h>
    2 #include <string.h>
    3 
    4 int main(void)
    5 {
    6     float a = 6.23;
    7     printf("%06.2f\n", a);
    8     return 0;
    9 }

      结果表明小数点占规定6位中的一位。

    6.puts函数

      关于puts函数要说明的就是它在输出一个字符串后会输出一个回车符进行换行。

      实例:

    View Code
     1 #include <cstdio>
     2 #include <cstring>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     char s[100];
     8     while(gets(s))
     9         puts(s)
    10     return 0;
    11 }

  • 相关阅读:
    JAVA常用知识总结(十一)——数据库(一)
    JAVA常用知识总结(十)——Maven
    JAVA常用知识总结(九)——线程
    JAVA常用知识总结(八)——计算机网络
    JAVA常用知识总结(七)——Spring
    Spring Cloud Alibaba教程:Nacos
    OpenCV入门(2)- Java第一个程序
    OpenCV入门(1)- 简介
    Elastic Job入门(1)
    Elastic Job入门(3)
  • 原文地址:https://www.cnblogs.com/xiaobaibuhei/p/3022096.html
Copyright © 2020-2023  润新知