Search code examples
carraysstringputchar

putchar() function: ambiguous output


Here is a simple code , trying to clear spaces from character array, but output is not like I did expect "YasserMohamed".

#include<stdio.h>

int main()
{
    char x[]="Yasser Mohamed";
    char ch;
    int i=0;
    while (x[i]!='\n')
    {
        if(x[i]!=' ')
            putchar(x[i]);
        i++;
    }
    system("pause");

    return 0 ;
}

Solution

  • There's no newline ('\n') in x. So, the condition is wrong and it should be:

    while (x[i]) /* until the null byte is found */
    {
        if (x[i] != ' ')
            putchar(x[i]);
        i++;
    }