read string with spaces in c code example

Example 1: how to get rid of all spaces in a string in c

#include<stdio.h>

char *remove_white_spaces(char *str)
{
    int i = 0, j = 0;
    while (str[i])
    {
        if (str[i] != ‘ ‘)
            str[j++] = str[i];
        i++;
    }
    str[j] = ‘\0;
    return str;
}

int main()
{
    char str[50];
    printf("\n\t Enter a string : ");
    gets(str);
    remove_white_spaces(str);
    printf(%s”,str);
    return 0;
}

Example 2: read string with space c

char name[30];
char temp;

printf("Enter age: ");
scanf("%d", &age);
printf("Enter name: ");
scanf("%c", &temp); // temp statement to clear buffer
scanf("%[^\n]", name); // read until newline

Tags:

Cpp Example