C Programming: Understanding `gets()` and `puts()`

beginner
24 min

C Programming: Understanding gets() and puts()

Welcome to another enlightening session at CodeYourCraft! Today, we're diving into the fascinating world of C Programming, exploring two essential functions - gets() and puts(). Let's get started! šŸŽÆ

What are gets() and puts()?

In C programming, gets() and puts() are standard library functions that facilitate input/output operations.

  • puts() is used for displaying strings on the screen.
  • gets() is used for reading strings from the keyboard.

šŸ“ Note: Always remember to include the header file <stdio.h> for using these functions.

puts() Function

Syntax

c
#include <stdio.h> int main() { puts("Hello, World!"); return 0; }

In the above code, puts() is used to print "Hello, World!" on the console. The function returns the number of characters (not including the null character) that were successfully written. For strings, it's always 1 more than the actual string length.

gets() Function

Syntax

c
#include <stdio.h> int main() { char name[20]; printf("Enter your name: "); gets(name); printf("Welcome, %s\n", name); return 0; }

In the above code, gets() is used to read a string from the user. The function reads characters from the standard input and stores them in the provided character array.

šŸ’” Pro Tip: Be cautious when using gets(), as it doesn't check for the limit of the array, which can lead to buffer overflow vulnerabilities.

Practical Examples

puts() Example

c
#include <stdio.h> int main() { puts("This is a simple example using puts() function."); return 0; }

gets() Example

c
#include <stdio.h> int main() { char name[20]; printf("Enter your name: "); gets(name); printf("Welcome, %s\n", name); return 0; }

Quiz Time!

Quick Quiz
Question 1 of 1

What does the `puts()` function do?

Quick Quiz
Question 1 of 1

What should you be careful about when using the `gets()` function?