介绍
今天,在本教程中,我们将讨论用于 C 和 C++ 编程语言的 **puts() 函数。
虽然在 C和 **C++**中的printf()
和cout
函数在打印变量、数字、行等方面都很突出,但在打印字符串时,它们最终会缺少,特别是printf()
。
puts() 函数在 C/C++ 中
**C/C++ **中的 puts()
函数用于将行或字符串写入输出(stdout
)流中. 它用 newline 打印过的字符串,并返回整数值。
puts()
函数声明在下面。
1int puts(const char* str);
在这里,str
是要打印的连续字符串。
让我们来看看一个小例子。
1#include<stdio.h>
2int main()
3{
4 //string initialisation
5 char Mystr[] = "C and C++";
6
7 puts(Mystr); //writing the string to stdout
8
9 return 0;
10}
出发点:**
1C and C++
正如你所看到的,我们的字符串Mystr
已成功打印到stdout
。下面的代码片段在 **C++**中也产生了相同的输出。
1#include<iostream>
2using namespace std;
3int main()
4{
5 //string initialisation
6 char Mystr[] = "C and C++";
7
8 puts(Mystr); //writing the string to stdout
9
10 return 0;
11}
在 C/C++ 中使用 puts() 函数
我们早些时候提到,puts()
函数在写字符串时附上一个新行字符。
1#include<stdio.h>
2int main()
3{
4 //string initialisation
5 char Mystr1[10] = "Python";
6 char Mystr2[10] = "Kotlin";
7
8 puts(Mystr1);
9 puts(Mystr2); //not specifically adding a newline
10
11 return 0;
12}
出发点:**
1Python
2Kotlin
在这里,我们已经初始化了两个字符串Mystr1
和Mystr2
。在使用puts()
方法在 C或 **C++**中打印这些字符串时,我们不必添加一个\n
(新字符串),因为函数已经添加了一个。
puts() 返回值
「puts()」函数返回成功执行的非负整数,否则返回任何错误的「EOF」。
下面的示例说明了puts()
函数的返回值。
1#include<stdio.h>
2int main()
3{
4 //string initialisation
5 char Mystr[] = "The puts() function";
6
7 int val = puts(Mystr);
8 printf("Returned Value Val = %d", val);
9
10 return 0;
11}
出发点:**
1The puts() function
2Returned Value Val = 0
puts() VS fputs() 函数在 C/C++ 中
正如我们之前所学到的,puts()函数将一行或一行字符串写入 stdout流中,而fputs()函数则用于写入任何 stream或一个 file,因此,这两个函数之间的最大区别在于,使用fputs()
,用户可以指定他想要写入的流。
此外,fputs()
函数不会将新行字符("\n"
)附加到经过的字符串/行的末尾。
结论
今天就這樣了!希望你有個滿意的學習經驗。
对于有关 C/C++ 中的 puts() 函数的任何进一步问题,请使用下面的评论。
参考
- C++ puts() - C++ 参照,
- C++ 教程,
- fgets() and gets() in C 编程,
- [在 C 中 printf() 和 puts() 之间有什么区别?(https://stackoverflow.com/questions/2454474/what-is-the-difference-between-printf-and-puts-in-c) - Stack Overflow 问题