This is a program that delete spaces in the beginning and the end of a string c, can you tell me please where is the error in it ? I already tried running it in the debuger. It seems that the while loops aren't executed, kind of neglecting.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
void main()
{
char c[1000],d[1000];
gets(c);
int i=0,j=strlen(c)-1;
while (c[i]==" ")
{
i ;
}
while (c[j]==" ")
{
j--;
}
int k,l=0;
for (k=i;k<=j;k )
{
d[l]=c[k];
l ;
}
printf(d);
}
CodePudding user response:
You should use single quotes to get a space character in C. If you use double quotes, you get a pointer to a string containing a space character and a null terminator, which is different.
So change " "
to ' '
.
Your compiler should have warned you about this, since you are comparing a char
to a const char *
. Indeed, when I compile your code in gcc
with the default options, it says:
test.c: In function 'main':
test.c:10:16: warning: comparison between pointer and integer
10 | while (c[i]==" ")
| ^~
test.c:14:16: warning: comparison between pointer and integer
14 | while (c[j]==" ")
| ^~
Your programming journey will be much easier if you pay attention to compiler warnings and fix them. You can also pass options like -Wall
to your compiler to make it give you more warnings.
Also you need to add a null terminator to your d
string. So add this line after the last loop:
d[l] = 0;