Augustus
Augustus

Reputation: 45

What's wrong in this program to remove extra spaces?

I tried to write a program to remove extra spacing. But it never returned the desired output. Can I know what's wrong here and how I can correct it?

#include<stdio.h>

main()
{
    char strin[150];
    int n,i;
    printf("Number of words : ");
    scanf("%d",&n);
    printf("Enter Input: ");
    for(i=0;i<n;i++)
    {
        scanf("%c",&strin[i]);

    }
    for(i=0;i<n;i++)
    {
        if(strin[i]==" ")
            continue;
        else
            printf("%c",strin[i]);
    }
}

Also I tried using %s instead of %c (with string.h header) but the run cmd crashed upon running it. Why does it crash?

Upvotes: 0

Views: 111

Answers (2)

Andy Sukowski-Bang
Andy Sukowski-Bang

Reputation: 1420

If you want to remove all spaces in the string and store it instead of just printing it, you can use this simple function:

void rmspaces(char *str)
{
    const char *dup = str;
    do {
        while (isspace(*dup)) {
            ++dup;
        }
    } while (*str++ = *dup++);
}

You can then call the function like this:

rmspaces(str);

Upvotes: 1

iamdhavalparmar
iamdhavalparmar

Reputation: 1218

Use ' ' instead of " " for checking a single character.

Use strcmp() to check more than one characters or whole string

Upvotes: 1

Related Questions