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:
- 参数str是写入标准输出流stdout的字符串,类型为char*。
cstdio库描述如下:
str
1. C string to be printed.
3 返回值
puts()函数的返回值类型为int型:
- 写入成功,返回一个非负数值;
- 写入失败,返回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’;
- 将空字符’\0’之前的所有字符依次写入标准输出流stdout;
- 当读到空字符’\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;
}
代码运行结果如下图所示: