QUESTION 30 · String Basics
Explain whole-line string input using fgets and safe newline handling.
5 marksAnswer in brief
fgets reads at most one less than the supplied positive capacity and adds a null terminator when successful. It is useful for whole-line input, including spaces.
Basic form
char line[80];
if (fgets(line, sizeof line, stdin) != NULL) {
/* use the successfully read string */
}
Newline handling
If the newline fits, fgets stores it before the terminator. strchr(line, '\n') can locate it so that it can be replaced with '\0'. Do not simply delete the last stored character without checking: input can end without a newline.
Length limit
This complete example accepts at most 79 text bytes. Its helper reads a bounded first portion. If no newline was stored, it checks the next input character: a newline or end of input means the line fit exactly or ended naturally. A longer line is drained and rejected, preventing a truncated prefix from being accepted as the whole answer.
Important points
A failed read must be handled before treating the buffer as new input. gets must not be used because it cannot enforce the destination capacity and is not part of modern standard C. scanf("%s", ...) stops at whitespace and is not equivalent to whole-line input.
Complexity and assumptions
Reading and checking a line of n bytes takes O(n) work. This fixed buffer uses bounded storage; a general capacity-m version needs O(m) buffer space. The helper is for ordinary text without embedded null bytes, not arbitrary binary input.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int read_line(char s[], int capacity)
{
if (fgets(s, capacity, stdin) == NULL) { return 0; }
char *newline = strchr(s, '\n');
if (newline != NULL) { *newline = '\0'; return 1; }
int ch = getchar();
if (ch == '\n' || ch == EOF) { return 1; }
while ((ch = getchar()) != '\n' && ch != EOF) { }
return 0;
}
int main(void)
{
char line[80];
if (!read_line(line, 80)) { puts("Invalid or overlong input"); return 1; }
printf("Line: %s\n", line);
return 0;
}
Sample input and output
Input
Hello students
Output
Line: Hello students