Skip to content
StudyFame

String Input and Output in C

Ask a user for their name with scanf("%s") and type Rahul Sharma. The program prints only Rahul! Where did "Sharma" go?

In this lesson you will learn the right way to read and print strings in C: scanf for single words, fgets for full lines with spaces, and printf/puts for output. You will also learn why gets() must never be used.

What You Will Learn

  • How to read one word with scanf("%s").
  • Why scanf stops at a space.
  • How to read a full line with fgets().
  • How to remove the newline that fgets keeps.
  • How to fix the "fgets skipped after scanf" problem.
  • How to print with printf and puts.

String Input and Output Functions in C

Exam definition: scanf("%s", s) reads a string up to the first whitespace (space, tab or newline). fgets(s, size, stdin) reads a whole line including spaces, at most size − 1 characters, and keeps the '\n'. puts(s) prints a string and adds a newline.

Memory trick: scanf reads a word (it is shy and stops at the first space). fgets = "full line gets": it takes the whole line and even grabs the Enter key.

FunctionReads spaces?Safe size limit?Note
scanf("%s", s)NoOnly with width: %19sOne word; no & needed
scanf("%[^\n]", s)YesOnly with width: %19[^\n]Reads until Enter
fgets(s, n, stdin)YesYesRecommended; keeps '\n'
gets(s)YesNoRemoved from C (C11): never use

Syntax for Reading and Printing Strings

char s[20];

scanf("%19s", s);              /* one word, at most 19 chars (no &) */
fgets(s, sizeof(s), stdin);    /* full line, at most 19 chars + '\0' */

printf("%s\n", s);             /* print, you add the newline */
puts(s);                       /* print + automatic newline */

Why no & with scanf("%s", s)? An array name already is an address (of its first element).

Example 1: Reading a String with scanf

#include <stdio.h>

int main(void)
{
    char name[30];

    printf("Enter your name: ");
    scanf("%29s", name);           /* stops at the space */

    printf("Hello, %s!\n", name);

    return 0;
}

Output

Enter your name: Rahul Sharma
Hello, Rahul!

Code Explanation

  1. char name[30]; reserves space for up to 29 letters plus '\0'.
  2. scanf("%29s", name); skips leading spaces, then reads letters until it meets whitespace. It reads "Rahul" and stops at the space.
  3. " Sharma" is not lost: it stays waiting in the input buffer for the next read.
  4. The 29 limits how many characters scanf stores, so a long input can't overflow the array.

How Keyboard Input Works (the Input Buffer)

When you type and press Enter, everything goes into a waiting area called the input buffer, including the Enter key as '\n'.

You type:  2 0 Enter R a h u l Enter
Buffer  :  '2' '0' '\n' 'R' 'a' 'h' 'u' 'l' '\n'

scanf("%d")  takes "20"         ->  '\n' is LEFT in the buffer
fgets(...)   sees '\n' at once  ->  reads an EMPTY line (looks "skipped")

Fix: after scanf, throw away the rest of the line before calling fgets:

while (getchar() != '\n')
    ;                          /* empty loop: eat characters up to Enter */

Example 2: Read a Full Name with fgets (After scanf)

#include <stdio.h>

int main(void)
{
    char name[30];
    int age, i;

    printf("Enter age: ");
    scanf("%d", &age);
    while (getchar() != '\n')          /* clear the leftover Enter */
        ;

    printf("Enter full name: ");
    fgets(name, sizeof(name), stdin);  /* reads spaces too */

    /* fgets keeps '\n': replace it with '\0' */
    for (i = 0; name[i] != '\0'; i++)
    {
        if (name[i] == '\n')
        {
            name[i] = '\0';
            break;
        }
    }

    printf("Name: %s, Age: %d\n", name, age);
    puts("Registration done.");

    return 0;
}

Output

Enter age: 20
Enter full name: Rahul Sharma
Name: Rahul Sharma, Age: 20
Registration done.
  • fgets(name, sizeof(name), stdin): stdin means "the keyboard". It reads at most 29 characters, so it can never overflow.
  • fgets stores "Rahul Sharma\n". Without removing '\n', the comma would print on the next line.
  • A shorter way to remove it (using string.h, next lesson): name[strcspn(name, "\n")] = '\0';
  • puts prints the text and moves to a new line by itself.

Why gets() is Dangerous

  • gets(s) doesn't know the size of s. If the user types more characters than the array holds, it writes into other memory (a buffer overflow).
  • Attackers used this to break into programs, so gets was removed in C11. Modern compilers warn about it or reject it.
  • Old textbooks still show gets. In exams you can mention it, but write fgets in real code.

Important Points to Remember

  • scanf("%s") reads one word and stops at whitespace.
  • No & before the array name in scanf("%s", s).
  • fgets reads a full line with spaces and is size-safe.
  • fgets keeps the '\n'; remove it if needed.
  • After scanf, clear the buffer before fgets.
  • Never use gets(); it was removed from C.
  • puts adds a newline; printf("%s") does not.

Common Mistakes Beginners Make

MistakeWhat happensFix
Reading a full name with scanf("%s")Only the first word is storedUse fgets
scanf("%s", &s)Works by luck but type is wrong; warningscanf("%s", s)
fgets right after scanf("%d")fgets reads an empty lineClear the buffer with a getchar loop
Forgetting fgets keeps '\n'Extra line break, string compare failsReplace '\n' with '\0'
Using fflush(stdin) to clear inputUndefined behaviour in standard CUse the getchar loop

String Input and Output Practice Questions

  1. Why does scanf("%s") read only "Rahul" from "Rahul Sharma"?
  2. Why is & not used with a string in scanf?
  3. What is the difference between gets and fgets?
  4. With char s[10];, at most how many characters does fgets(s, 10, stdin) store before '\0'?
  5. What is the difference between puts(s) and printf("%s", s)?
Show answers
  1. %s stops reading at the first whitespace (the space).
  2. The array name already gives the address of its first element.
  3. gets has no size limit (buffer overflow risk, removed in C11); fgets takes a size and keeps the newline.
  4. 9 characters.
  5. puts adds a newline automatically; printf doesn't.

Coding Exercise

Read a full sentence with fgets and print how many spaces it has and how many words (assume single spaces between words). Test with "I love C programming".

Show solution
#include <stdio.h>

int main(void)
{
    char s[100];
    int i, spaces = 0;

    printf("Enter a sentence: ");
    fgets(s, sizeof(s), stdin);

    for (i = 0; s[i] != '\0' && s[i] != '\n'; i++)
    {
        if (s[i] == ' ')
            spaces++;
    }
    printf("Spaces: %d\n", spaces);
    printf("Words : %d\n", spaces + 1);
    return 0;
}
Enter a sentence: I love C programming
Spaces: 3
Words : 4

For text with extra spaces, see count total number of words in a text.

Quick Quiz: String Input and Output (MCQ)

  1. scanf("%s", s) stops reading at:

    A) The end of the line only   B) The first whitespace   C) 10 characters   D) A comma

  2. Which function is safe for reading a line?

    A) gets   B) fgets   C) puts   D) getch

  3. fgets stores the Enter key as:

    A) Nothing   B) '\0'   C) '\n'   D) ' '

  4. gets() was removed in which C standard?

    A) C89   B) C99   C) C11   D) C17

  5. Which prints a string followed by a newline automatically?

    A) printf   B) puts   C) putchar   D) scanf

Show answers
  1. B: the first whitespace.
  2. B: fgets.
  3. C: '\n'.
  4. C: C11.
  5. B: puts.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

scanf("%s")Reads one word, stops at whitespace
& with string?No: name is already an address
fgets(s, n, stdin)Full line, max n − 1 chars, keeps '\n'
gets()Unsafe, removed in C11
fgets skipped?Leftover '\n' from scanf: clear the buffer
puts(s)Prints + newline

Frequently asked questions

How do you read a string with spaces in C?
Use fgets(s, sizeof(s), stdin) (or scanf("%[^\n]", s)).
What is the difference between gets and fgets?
fgets takes a size limit and keeps '\n'; gets has no limit and can cause buffer overflow.
Why does fgets not wait for input after scanf?
scanf leaves the '\n' in the buffer, and fgets reads it as an empty line.

Remember

  • scanf = word; fgets = full line.
  • gets = never.

Next Topic

Next lesson: String Functions in C (string.h). You will use ready-made string functions like strlen, strcpy, strcat and strcmp.