A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
scanf("%s", buf) stops at the first whitespace character. If the user types "John Smith", scanf reads "John" and leaves " Smith" in the input buffer. The next read picks up "Smith" as if it were a separate input. This is almost never what you want for names, addresses, or sentences. fgets reads an entire line including spaces, up to a buffer size limit. It is the correct tool for line-oriented input.
#include <stdio.h>int main(void) {char first[50], second[50];printf("Enter your full name: ");scanf("%s", first);scanf("%s", second);printf("First token: \"%s\"\n", first);printf("Second token: \"%s\"\n", second);return 0;}
One line of input, two scanf calls. The space split the name. If you only had one scanf, "Smith" would sit in the buffer and contaminate the next input operation. This is the source of countless "my program skips the next input" bugs.
#include <stdio.h>#include <string.h>int main(void) {char name[100];printf("Enter your full name: ");if (fgets(name, sizeof(name), stdin) == NULL) {printf("No input received.\n");return 1;}name[strcspn(name, "\n")] = '\0';printf("Full name: \"%s\"\n", name);printf("Length: %zu\n", strlen(name));return 0;}
fgets reads the entire line including spaces. It stops at a newline or when the buffer is full (leaving room for the null terminator). The newline is included in the buffer, which is why we strip it with strcspn. That strcspn trick finds the newline and replaces it with \0 in one operation. No loop. No branching.
If the user types more characters than the buffer can hold, fgets fills the buffer, null-terminates it, and leaves the excess in the input stream. The next fgets call reads the remainder. Your program sees the input split across two reads. To detect this, check whether the buffer contains a newline. If it does not and the input was not EOF, the line was truncated.
Never use gets(). It has no buffer size parameter. It cannot prevent overflow. It was removed from the C11 standard. Any code using gets() is a security vulnerability. Use fgets with an explicit size. Always.
fgets is the safe, standard way to read lines in C. It bounds the read. It handles spaces. It reports failure via NULL. The newline stripping is a one-liner. There is no reason to use anything else for line input. Next: strcpy and strncpy, the string copy functions and their well-known pitfalls.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.