To read a string input that includes spaces using scanf() in C, you can use the fgets() function instead. The scanf() function with the %s format specifier stops reading at the first whitespace, which means it won't capture spaces. Here's how you can use fgets():
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s", str);
return 0;
}
Explanation:
fgets(str, sizeof(str), stdin);reads a line of text from standard input, including spaces, until a newline character is encountered or the specified limit is reached.- This method is safer than
scanf()for reading strings, as it prevents buffer overflow by limiting the number of characters read.
