Search code examples
cstringnull-character

Printing a string with null characters in it


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?


Solution

  • Your code is wrong.

    for(i=0;i<length;i++){
            if(a[i] == " ")
                    a[i] = '\0';
    }   
    

    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

    for(i=0;i<length;i++){
            if(a[i] == ' ')
                    a[i] = '\0';
    }   
    

    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)

    for(i=0;i<length;i++){
               if(isspace(a[i]))
                    a[i] = '\0';
    }