【C语法学习】8 - puts()函数

1 函数原型

puts():将str指向的内存空间中存储的字符串写入到标准输出流stdout,函数原型如下:

int puts(const char *str)

cstdio库描述如下:

1. Write string to stdout.
2. Writes the C string pointed by str to the standard output (stdout) and appends a newline character ('\n').
3. The function begins copying from the address specified (str) until it reaches the terminating null character ('\0').
4. This terminating null-character is not copied to the stream.
5. 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库描述如下:

1. C string to be printed.

3 返回值

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

  1. 输出成功,返回一个非负数值(vs2019中返回0);
  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()函数发送字符到标准输出流stdout,直至遇到空字符’\0’:

  1. 读取str指向的内存空间中存储的字符串;
  2. 发送空字符’\0’之前的所有字符,包括空格、制表符等字符;
  3. 将空字符’\0’替换为换行符’\n’并输出。

特别说明:puts()函数与gets()函数刚好相反,gets()函数将换行符’\n’转换为空字符’0’,而puts()函数将空字符’\0’转换为换行符’\n’。

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、付费专栏及课程。

余额充值