reading string with spaces in c

To read a string with spaces in C, you can use the fgets() function from the standard input library. Here's an example code snippet:

#include <stdio.h>

int main() {
    char str[100]; // assuming the string length is 100 characters

    printf("Enter a string with spaces: ");
    fgets(str, sizeof(str), stdin);

    printf("You entered: %s\n", str);

    return 0;
}

In this example, the fgets() function reads the input from the user until a newline character is encountered or the maximum number of characters specified (99 in this case). It stores the input string, including any spaces, into the str variable.

The printf() function is then used to display the entered string. Finally, the program returns 0 to indicate successful execution.

Note that fgets() includes the newline character in the input string if it is encountered before reaching the maximum character limit. To remove the newline character, you can use the strcspn() function, like this:

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

int main() {
    char str[100]; // assuming the string length is 100 characters

    printf("Enter a string with spaces: ");
    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0'; // remove the newline character

    printf("You entered: %s\n", str);

    return 0;
}

In this modified example, the strcspn() function is used to find the position of the newline character (\n) in the string and replace it with a null character (\0), effectively removing it from the string before displaying it.