+ 1
what is wrong with this code?
//program to remove spaces from a string #include <stdio.h> #include <string.h> int main() { char str[50], str1[50]; fgets(str, 20, stdin); int l= strlen(str); printf("%d\n", l); int j=0; for(int i=0; i<=l-2; i++){ while(str[i]!= 32){ // ASCII value of [space] is 32 str1[j]= str[i]; j++; } } printf("%s\n", str1); return 0; } //Its showing no ouput. why?
3 Answers
+ 1
First loop loops the string to length - 1. I think you want it to copy entire string if i < length. You then copy from str to str1 while there is no space at str[i].
the inner while-loop do not increment i ,so checking str[i] will check same character in str is not space... and loop runs forever. The problem is that the inner loop increases j and it overrun str1's buffer.
Even if you fix inner loop to increment i, you have another problem, inner loop will run until it finds no space but doesn't care if null byte is reached (string has ended). It would overrun both strings.
It would be easier changing inner loop to skip the index when space is found and copy next character from str:
while (str[i] == 32)
i++;
str1[j++] = str[i];
hope it helps.
+ 1
Thankyou dear Gen2oo
I've tried this... It worked
Instead of while, using if solves the problem completely
đ
+ 1
Russel's
Yes that works. Just remember, add null-byte at end of str1 when its done copying because the copied string is not terminated.