Home>Article>Backend Development> What is the role of the C language string output function puts()
The functions of the C language string output function puts(): 1. [puts()] will automatically add a newline character at the end of the string when displaying it; 2. [puts()] encounters an empty string The output stops when a character is reached, so you must ensure that there are null characters.
[Related learning recommendations:C language tutorial video]
C The role of the language string output function puts():
puts()will automatically add a newline character at the end of the string when it is displayed.
puts()Stops output when encountering a null character, so you must ensure that there is a null character.
The following two examples illustrate the two characteristics of puts() respectively.
Example 1:
/* put_out.c -- using puts() */ #include#define DEF "I am a #defined string." int main(void) { char str1[80] = "An array was initialized to me."; const char * str2 = "A pointer was initialized to me."; puts("I'm an argument to puts()."); puts(DEF); puts(str1); puts(str2); puts(&str1[5]); puts(str2+4); return 0; }
The output of this program is as follows:
I'm an argument to puts(). I am a #defined string. An array was initialized to me. A pointer was initialized to me. ray was initialized to me. inter was initialized to me.
As shown above, each string is on its own line because puts() will Automatically adds a newline character at the end.
Example 2:
/* nono.c -- no! */ #includeint main(void) { char side_a[] = "Side A"; char dont[] = {'W', 'O', 'W', '!' }; char side_b[] = "Side B"; puts(dont); /* dont is not a string */ return 0; }
The following is an example of this program. The results may be different every time it is run. The content output by different compilers may be different:
WOW!Side A
How does puts() know where to stop? This function stops output when it encounters a null character. Since dont lacks a terminating null character, it is not a string, so puts() doesn't know where to stop. It will keep printing the content in the memory after dont until a null character is found. In order to allow puts() to read the null character as quickly as possible, we put dont betweenside_a
andside_b
. The above is a running example of the program, output by different compilers Content may vary
The above is the detailed content of What is the role of the C language string output function puts(). For more information, please follow other related articles on the PHP Chinese website!