fgets respects buffer capacity
parola has capacity 8: fgets can read at most 7 characters and keeps one cell for \0. With CIAO + Enter, the written prefix is C I A O \n \0.
C programming · Lesson
Read a line into a known-size buffer and observe how to handle the newline without writing past its bounds.
fgets also receives the buffer capacity: with char parola[8] it can store at most 7 characters plus the terminator. If the user presses Enter before filling the buffer, the newline can become part of the string and must be handled explicitly.
char parola[8] → fgets(..., sizeof parola, ...) → find \n or \0 → replace \n with \0 → use the string
The flowchart shows the logical string value; the String Memory Explorer below shows the individual char cells and the \0 terminator actually required in C.
Each cell contains one char. The \0 terminator occupies a real cell and tells C functions where the string ends.
parola has capacity 8: fgets can read at most 7 characters and keeps one cell for \0. With CIAO + Enter, the written prefix is C I A O \n \0.
The loop looks for the first \n or \0. It starts at index 0.
The first four characters are neither newline nor terminator, so i advances to 4.
parola[4] contains \n: the loop stops before the original terminator in parola[5].
The newline is replaced with \0. From this point the logical string ends at parola[4].
printf with %s reads CIAO and stops at the new terminator at index 4.
Run C executes only the example shown on the left, using stdin on the right. The coding challenge below has a separate editor and test button.
1#include <stdio.h>
2
3int main(void)
4{
5 char parola[8];
6
7 if (fgets(parola, sizeof parola, stdin) == NULL)
8 return 1;
9
10 int i = 0;
11 while (parola[i] != '\0' && parola[i] != '\n')
12 {
13 i = i + 1;
14 }
15
16 if (parola[i] == '\n')
17 {
18 parola[i] = '\0';
19 }
20
21 printf("%s\n", parola);
22 return 0;
23}
Use fgets to read up to 50 chars and print length excluding optional newline.
This is a different program from lab 1. Complete the starter code: Check all test cases compiles this editor and tests every input, including boundary cases.
With char parola[8], how many characters can fgets read at most while leaving room for the terminator?
Challenge 1 / 5 · Understanding
Progress: 0 / 5 · correct: 0
ConceptStep separates what is required from what is recommended or useful as reinforcement. Only required prerequisites block your progress.
Relationships: solid line = required · dashed line = recommended · dotted line = reinforcement.