C String I/O

Beginner
6 min read
Updated: Nov 2026
1 example

What Is String Input and Output?

Output uses printf("%s") or puts. For input, prefer fgets into a sized buffer over scanf("%s"), which can overflow and stops at whitespace.

Remember
char line[64];
fgets(line, sizeof line, stdin);  /* keeps newline if it fits */
puts(line);                       /* adds its own newline */

Cheat Sheet

TopicDetail
Printprintf("%s", s); / puts(s);
Read linefgets(buf, n, stdin);
Avoidgets — removed; never use
scanf %sSkips leading space; no spaces; risk of overflow without width

C Examples

Compile with gcc file.c -std=c11 -Wall -o out. Next: String Operations.

Example 1

C
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[32] = "Guest";
    printf("Hello, %s\n", name);
    puts("Enter a short word:");
    if (fgets(name, sizeof name, stdin) != NULL) {
        name[strcspn(name, "\n")] = '\0'; /* strip newline */
        printf("You typed: %s\n", name);
    }
    return 0;
}

How It Works

  1. printf prints the current name.
  2. fgets reads up to sizeof name - 1 chars and adds \0.
  3. strcspn finds the newline so we can replace it with \0.

Edge Cases & Pitfalls

gets

Never use gets

gets cannot bound the write — it was removed from the C standard.

newline

fgets keeps `\n`

Strip it when you need a clean string without the line break.

Key Takeaways

  • Out: printf("%s") and puts.
  • In: fgets with a real buffer size.
  • Bound: never read unbounded string input.

One line: Print with %s/puts; read lines with fgets into a sized buffer.

Frequently Asked Questions

It stops at whitespace and can overflow unless you set a width like %31s. fgets is clearer for whole lines.
Yes. puts(s) writes s then a newline. printf("%s\n", s) does the same explicitly.
String Operations covers copy, length, and compare with string.h.

Next: String Operations

Continue the C strings track.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful