Search code examples
cloopswhile-loopc-stringsgetchar

Random characters printed after printing 'result'


I'm getting random characters after the actual output in printf("%s",result);. Why are these characters being printed? And how can I remove them?

#include<stdio.h>
char *replacechar(char[]);

int main()
{
    char str[25];
    char *result;
    int i=0;
    while( (str[i++]=getchar()) != '\n' && i < 25);
    result= replacechar(str);
    printf("%s",result);
    return 0;
}

char *replacechar(char str[])
{
    return str;
}

Expected Output:

aaayt
aaayt

Actual Output:

aaayt
aaayt
↑@

Solution

  • For starters the operands of the condition

    (str[i++]=getchar()) != '\n' && i < 25
    

    should be swapped.

    i < 25 && (str[i++]=getchar()) != '\n'
    

    The input stored in the character array str should be zero-terminated. Otherwise the array will not contain a string.

    Here is a demonstrative program that shows how your code can be rewritten

    #include <stdio.h>
    
    char *replacechar( char str[] )
    {
        return str;
    }
    
    int main(void) 
    {
        enum { N = 25 };
        char str[N];
        char *result;
    
        size_t i = 0;
    
        while( i < N - 1 && ( str[i] = getchar() ) != '\n' ) i++;
    
        str[i] = '\0';
    
        result = replacechar( str );
    
        puts( result ); 
    
        return 0;
    }
    

    Its output might look like

    Hello Siddharth Awana
    Hello Siddharth Awana