puts function in C Programming

puts function

It is used to display a string on a standard output device. The puts() function automatically inserts a newline character at the end of each string it displays, so each subsequent string displayed with puts() is on its own line. puts() returns non-negative on success, or EOF on failure.

The following program illustrates the use of puts function.

The `puts()` function in C is used to write a string to the standard output (usually the console) followed by a newline character. It is part of the standard input-output library `stdio.h`.

Syntax:

int puts(const char *str);

Parameters:

  • `str`: A pointer to the null-terminated string to be written to the standard output.

Return Value:

  • On success, it returns a non-negative value.
  • On failure, it returns `EOF` (defined in `stdio.h`).

Example Usage:

#include <stdio.h>

int main() {
    char str[] = "Hello, world!";
    puts(str);

    return 0;
}

Output:

Hello, world!

Important Notes:

  • `puts()` writes the string pointed to by `str` to the standard output, followed by a newline character (`'\n'`).
  • It is typically used for simple string output when a newline character is desired after the string.
  • Unlike `printf()`, `puts()` does not support formatting options or multiple arguments. It only accepts a single string argument.
  • It automatically appends a newline character to the output, which means you don't need to explicitly add `'\n'` to the string.
  • If the function encounters an error during output, it returns `EOF`.

Alternatives:

  • `printf()`: For more advanced formatting and writing multiple values, `printf()` provides extensive formatting options.
  • `fputs()`: Similar to `puts()`, but allows writing strings to a specified file stream instead of the standard output.

`puts()` is a simple and convenient function for writing strings to the standard output with a newline character appended. It's commonly used in simple text-based programs and scripts for straightforward output operations.

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!