Search code examples
cc-strings

Write a program in C that removes leading and trailing spaces from a string


This is a problem from the Data Structures and Algorithms textbook by Thareja. I am trying to solve the problems to be prepared for my Data Structures class. I am compiling and running this at https://www.onlinegdb.com/online_c_compiler. My program is coming to a segmentation fault and it is never entering the if statement(I cannot seem to find out why). The issue is possibly trivial and I am overlooking it but I would like another set of eyes to take a look at it.

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

int main()
{
    char str[100],ans[100];
    int i=0,j=0;
    clrscr();
    printf("\nEnter string: ");
    gets(str);

    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            i++;
            continue;
        } 
        ans[j]=str[i];
        j++;
    }
    ans[j]='\0';
    printf("\nThe string is: ");
    puts(ans);
    getch();
    return 0;
}

Thanks for the help.


Solution

  • To me it looks like the problem is with increment operator on variable i. Lets assume, the string user entered is not null and there is no leading space(s). In this case, your code enters while loop successfully (coz it couldn't find a null character) and next thing it checks if is a blank space (str[i]==' ') , which according to assumption is not so it moves on to store the character in in ans[j]. At this point everything looks okay but the program moves to next line your code increments j but what about i? By not incrementing i you're making while loop to enter an infinite loop. Hope this helps.