fgets()函数和fputs()函数 您所在的位置:网站首页 fgets函数的例子 fgets()函数和fputs()函数

fgets()函数和fputs()函数

2023-11-22 13:56| 来源: 网络整理| 查看: 265

文章目录 前言一、gets()函数和puts()函数二、gets()的替代品三、 fgets()函数和fputs()函数

前言

在读取字符串时,scanf ()和转换说明%s只能读取一个单词。可是在程序中经常要读取一整行输入,而不仅仅是一个单词。许多年前,gets()函数就用于处理这种情况。gets ()函数简单易用,它读取整行输入,直至遇到换行符,然后丢弃换行符,储存其余字符,并在这些字符的末尾添加一个空字符使其成为一个C字符串。

一、gets()函数和puts()函数

gets()函数经常和 puts ()函数配对使用,该函数用于显示字符串,并在末尾添加换行符。下面演示了这两个函数的用法。

#define STLEN 81 int main (void) { char words [STLEN] ; puts ("Enter a string, please.") ; gets (words) ;//典型用法 printf ("Your string twice: n") ; printf ("%s)n", words) ; puts (words) ; puts ("Done.") ; return O; }

下面是该程序在某些编译器(或者至少是旧式编译器)中的运行示例:

Enter a string, please . I want to learn about string theory ! Your string twice: I want to learn about string theory! I want to learn about string theory! Done .

整行输入(除了换行符)都被储存在words中,puts (words)和printf (“&s\n,words”) 的效果相同。

二、gets()的替代品

过去通常用fgets()来代替gets(),fgets ()函数稍微复杂些,在处理输入方面与gets()略有不 同。C11标准新增的gets_ s()函数也可代替gets().该函数与gets ()函数更接近,而且可以替换现有代码中的gets()。但是,它是stdio.h输入/输出函数系列中的可选扩展,所以支持C11的编译器也不一定支持它。

三、 fgets()函数和fputs()函数

fgets()函数通过第2个参数限制读入的字符数来解决溢出的问题。该函数专门设计用于处理文件输 入,所以一-般情况下可能不太好用。fgets() 和gets()的区别如下。

■fgets()函数的第2个参数指明了读入字符的最大数量。如果该参数的值是n,那么fgets()将 读入n-1个字符,或者读到遇到的第-一个 换行符为止。

如果fgets()读到-一个换行符,会把它储存在字符串中。这点与gets()不同,gets() 会丢弃换行符。

■ fgets()函数的第3个参数指明要读入的文件。如果读入从键盘输入的数据,则以stdin (标准输入)作为参数,该标识符定义在stdio.h中。

因为fgets() 函数把换行符放在字符串的末尾(假设输入行不溢出),通常要与fputs()函数 (和puts ()类似)配对使用,除非该函数不在字符串末尾添加换行符。fputs ()函数的第2个参数指明它要写 入的文件。如果要显示在计算机显示器上,应使用stdout (标准输出)作为该参数。下列程序演示 了fgets ()和fputs ()函数的用法。

#include #define STLEN 14 int main (void) { char words [STLEN] ; puts("Enter a string, please.") ; fgets (words,STLEN, stdin) ; printf ("Your string twice (puts(), then fputs()) :\n") ; puts (words) ; fputs (words, stdout); puts("Enter another string, please.") ; fgets (words, STLEN, stdin) ; printf ("Your string twice (puts(), then fputs()) :\n") ; puts (words) ; fputs (words,stdout) ; puts ("Done.") ; return 0; }

下面是该程序的输出示例:

Enter a string, please. app1e pie Your string twice (puts(), then fputs()): apple pie apple pie Enter another string, please. strawberry shortcake Your string twice (puts(), then fputs()) : strawberry sh strawberry shDone.

第1行输入,apple pie, 比fgets ()读入的整行输入短,因此,apple pie\n\0 被储存在数组中。 所以当puts ()显示该字符串时又在末尾添加了换行符,因此apple pie后面有一 -行空行。因为fputs ()不在字符串末尾添加换行符,所以并未打印出空行。

第2行输入,strawberry shortcake,超过了大小的限制,所以fgets()只读入了13个字符,并把 strawberry sh\o 储存在数组中。再次提醒读者注意,puts ()函数会在待输出字符串末尾添加一一个换行符,而fputs()不会这样做。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有