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
scanfstops 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
printfandputs.
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.
| Function | Reads spaces? | Safe size limit? | Note |
|---|---|---|---|
scanf("%s", s) | No | Only with width: %19s | One word; no & needed |
scanf("%[^\n]", s) | Yes | Only with width: %19[^\n] | Reads until Enter |
fgets(s, n, stdin) | Yes | Yes | Recommended; keeps '\n' |
gets(s) | Yes | No | Removed 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
char name[30];reserves space for up to 29 letters plus'\0'.scanf("%29s", name);skips leading spaces, then reads letters until it meets whitespace. It reads "Rahul" and stops at the space.- " Sharma" is not lost: it stays waiting in the input buffer for the next read.
- The
29limits 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):stdinmeans "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'; putsprints the text and moves to a new line by itself.
Why gets() is Dangerous
gets(s)doesn't know the size ofs. 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
getswas 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). fgetsreads a full line with spaces and is size-safe.- fgets keeps the '\n'; remove it if needed.
- After
scanf, clear the buffer beforefgets. - Never use gets(); it was removed from C.
putsadds a newline;printf("%s")does not.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Reading a full name with scanf("%s") | Only the first word is stored | Use fgets |
scanf("%s", &s) | Works by luck but type is wrong; warning | scanf("%s", s) |
fgets right after scanf("%d") | fgets reads an empty line | Clear the buffer with a getchar loop |
Forgetting fgets keeps '\n' | Extra line break, string compare fails | Replace '\n' with '\0' |
Using fflush(stdin) to clear input | Undefined behaviour in standard C | Use the getchar loop |
String Input and Output Practice Questions
- Why does
scanf("%s")read only "Rahul" from "Rahul Sharma"? - Why is
¬ used with a string in scanf? - What is the difference between
getsandfgets? - With
char s[10];, at most how many characters doesfgets(s, 10, stdin)store before'\0'? - What is the difference between
puts(s)andprintf("%s", s)?
Show answers
%sstops reading at the first whitespace (the space).- The array name already gives the address of its first element.
getshas no size limit (buffer overflow risk, removed in C11);fgetstakes a size and keeps the newline.- 9 characters.
putsadds a newline automatically;printfdoesn'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)
-
scanf("%s", s)stops reading at:A) The end of the line only B) The first whitespace C) 10 characters D) A comma
-
Which function is safe for reading a line?
A)
getsB)fgetsC)putsD)getch -
fgets stores the Enter key as:
A) Nothing B)
'\0'C)'\n'D)' ' -
gets()was removed in which C standard?A) C89 B) C99 C) C11 D) C17
-
Which prints a string followed by a newline automatically?
A)
printfB)putsC)putcharD)scanf
Show answers
- B: the first whitespace.
- B:
fgets. - C:
'\n'. - C: C11.
- 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.