I take as input a string with spaces in it and replace the spaces with the NULL character ‘\0’. When I print the string now, I expect only the part till the first NULL character which was the first space earlier but I am getting the original string.
Here is the code-
#include<stdio.h>
int main(){
char a[1000];
int length, i = 0;
length = 0;
scanf("%[^\n]s", a);
while(a[i]!='\0')
i++;
length = i;
printf("Length:%d\n", length);
printf("Before:%s\n", a);
for(i=0;i<length;i++){
if(a[i] == " ")
a[i] = '\0';
}
printf("After:%s\n", a);
return 0;
}
What is wrong in this?
Your code is wrong.
The comparison is trying to compare a character with a pointer (denoted by ” ” ->This becomes a pointer to a string of characters. In this case the string is only having a space.)
This can be fixed by the following replacement
Or better to do it in this manner, since you can have other whitespace too like tab, apart from space.
(Please include ctype.h also)