0
0
CHow-ToBeginner · 3 min read

How to Read String with Spaces in C: Simple Guide

To read a string with spaces in C, use fgets() which reads the entire line including spaces. Alternatively, use scanf("%[^ ]", str) to read until a newline character, capturing spaces as well.
📐

Syntax

fgets() reads a line from input including spaces until a newline or buffer limit.

  • char *fgets(char *str, int n, FILE *stream);
  • str: buffer to store input
  • n: max characters to read including null terminator
  • stream: input source, usually stdin

scanf() with %[^ ] reads characters until newline, including spaces.

  • scanf("%[^ ]", str);
  • Stops reading at newline but includes spaces
c
char *fgets(char *str, int n, FILE *stream);

// Using scanf to read string with spaces
scanf("%[^
]", str);
💻

Example

This example shows how to read a full line with spaces using fgets() and then print it.

c
#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string with spaces:\n");
    fgets(str, sizeof(str), stdin);
    printf("You entered: %s", str);
    return 0;
}
Output
Enter a string with spaces: Hello world from C You entered: Hello world from C
⚠️

Common Pitfalls

Using scanf("%s", str) reads only until the first space, so it stops early. Also, fgets() keeps the newline character, which may need removal.

Example of wrong and right ways:

c
#include <stdio.h>
#include <string.h>

int main() {
    char str1[100];
    char str2[100];

    printf("Using scanf with %s (wrong):\n");
    scanf("%s", str1);
    printf("Result: %s\n", str1);

    // Clear input buffer
    int c;
    while ((c = getchar()) != '\n' && c != EOF) {}

    printf("Using fgets (right):\n");
    fgets(str2, sizeof(str2), stdin);
    // Remove newline if present
    str2[strcspn(str2, "\n")] = '\0';
    printf("Result: %s\n", str2);

    return 0;
}
Output
Using scanf with %s (wrong): Hello world Result: Hello Using fgets (right): Hello world Result: Hello world
📊

Quick Reference

  • Use fgets() to read strings with spaces safely.
  • Remember to remove newline character from fgets() input if needed.
  • scanf("%[^ ]", str) reads until newline including spaces but beware of leftover newline in input buffer.
  • Avoid scanf("%s", str) for strings with spaces.

Key Takeaways

Use fgets() to read strings with spaces including the newline character.
Remove the trailing newline from fgets() input if you want a clean string.
scanf("%[^ ]", str) reads until newline and includes spaces but requires careful buffer handling.
Avoid scanf("%s", str) for input with spaces as it stops at the first space.
Always ensure your input buffer is large enough to hold the expected string.