8 - puts()函数

1 函数原型

puts():将字符串写入标准输出流stdout,函数原型如下:

int puts(const char *str);

cstdio库描述如下:

Write string to stdout
1. Writes the C string pointed by str to the standard output (stdout) and appends a newline character ('\n').
2. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0').
3. This terminating null-character is not copied to the stream.
4. Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not).

2 参数

puts()函数只有一个参数str:

  1. 参数str是一个指向字符串的指针,类型为char*;str指向的字符串可以是字符数组或字符串常量。

cstdio库描述如下:

str
1. C string to be printed.

3 返回值

puts()函数的返回值类型为int型:

  1. 写入成功,返回一个非负数值;
  2. 写入失败,返回EOF。

cstdio库描述如下:

1. On success, a non-negative value is returned.
2. On error, the function returns EOF and sets the error indicator (ferror).

4 写入机制

puts()函数从str指向的地址开始依次读取字符,直至遇到字符串结束符即空字符’\0’;

  1. 将空字符’\0’之前的所有字符写入标准输出流stdout;
  2. 当读到空字符’\0’时,将空字符’\0’丢弃,并自动在字符串的末尾添加一个换行符’\n’。

特别说明:puts()函数的写入机制与gets()函数的读取机制刚好相反。

5 示例

以字符数组和字符串常量的形式输出字符串,示例代码如下所示:

int main()
{
   //
   char str[20] = "hello world";
   int  ret = 0;
   //
   ret = puts(str);
   //
   printf("Return value is %d\n", ret);
   //
   ret = puts("i love you xduryan");
   //
   printf("Return value is %d\n", ret);
   //
   return 0;
}

代码运行结果如下所示:

在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值