← Back to C Course | Chapter 2: Input & Output | Lesson 6 of 7

C puts() and gets()

What is puts()?

puts() prints a string followed automatically by a newline, making it a slightly simpler alternative to printf when you just need to display fixed text without any variable substitution or formatting.

Example: What is puts()?

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

Using puts() vs. printf()

puts() is easier to use than printf for plain text output since it takes no format specifiers, but it also can't interpolate variable values into the middle of a string the way printf's %d, %s, and similar placeholders can.

Example: Using puts() vs. printf()

c
#include <stdio.h>
int main() {
	puts("Fixed text, no formatting");
	printf("Age: %d\n", 25);
	return 0;
}

Reading Text safely with fgets()

gets() is deprecated and removed from modern C standards because it has no way to limit how much input it reads, letting a user's input overflow the buffer and corrupt adjacent memory -- fgets() replaces it safely by taking a maximum length.

Example: Reading Text safely with fgets()

c
#include <stdio.h>
#include <string.h>
int main() {
	char buffer[20] = "Sample text\n";
	printf("%s", buffer);
	return 0;
}

Understanding Gets and Buffer Sizes

Unlike fgets(), the old gets() function never checks whether the destination buffer is large enough for the input being typed, which is exactly the security flaw that makes it unsafe to use in any real program.

Example: Understanding Gets and Buffer Sizes

c
#include <stdio.h>
int main() {
	char buffer[10];
	// gets(buffer) would not check if input fits in buffer -- unsafe
	printf("Use fgets(buffer, sizeof(buffer), stdin) instead");
	return 0;
}

Cleaning Newlines from Input

fgets() includes the trailing newline character in the buffer it reads, unlike gets() which discards it -- if your code compares that string against something without a newline, you'll need to strip it first, often with strcspn or manual indexing.

Example: Cleaning Newlines from Input

c
#include <stdio.h>
#include <string.h>
int main() {
	char buffer[20] = "Hello\n";
	buffer[strcspn(buffer, "\n")] = '\0';
	printf("[%s]", buffer);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.