puts()函数
puts函数是C语言中的一个标准库函数,用于向标准输出流(即控制台)输出字符串。
它的函数原型如下:
int puts(const char *str);
函数参数:
- str:要输出的字符串。
函数返回值:
- 如果成功输出字符串,则返回非负值;
- 如果输出失败,则返回EOF(-1)。
puts函数会在所输出的字符串末尾自动追加一个换行符('\n'),这与printf函数不同。因此,使用puts函数输出字符串时无需手动添加换行符。
示例用法:
#include <stdio.h>
int main() {
char str[] = "Hello, world!";
puts(str);
puts(str);
return 0;
}
结果
Hello, world!
Hello, world!
以上代码会在控制台输出"Hello, world!",并在末尾自动添加换行符。
此外注意,gets()丢弃输入中的换行符,但是puts()在输出中添加换行符
fputs()函数
fputs函数是C语言中的一个标准库函数,用于向指定的文件流输出字符串。
它的函数原型如下:
int fputs(const char *str, FILE *stream);
函数参数:
- str:要输出的字符串。
- stream:指向要输出到的文件流的指针。如果我们要打印在显示器上,可以用定义在stdio.h中的stdout(标准输出)作为该参数
函数返回值:
- 如果成功输出字符串,则返回非负值;
- 如果输出失败,则返回EOF(-1)。
与puts函数不同的是,fputs函数不会自动追加换行符,输出的字符串就是原样输出。
示例用法:
#include <stdio.h>
int main(void)
{
char str[] = "Hello, world!";
fputs(str,stdout);
fputs(str,stdout);
return 0;
}
结果
Hello, world!Hello, world!
printf()输出字符串
printf()函数是C语言中的一个输出函数,用于在终端或控制台上打印输出内容。它可以输出各种类型的数据,包括字符串。下面是一个例子:
#include <stdio.h>
int main() {
char str[] = "Hello, world!"; // 定义一个字符串变量
printf("%s\n", str); // 使用%s格式控制符输出字符串
return 0;
}
运行这段代码会输出字符串"Hello, world!"。
其中,%s
是格式控制符,用于输出字符串类型的数据。在printf()
函数中,用%s
代表需要输出的字符串,\n
表示换行符。