Search code examples
cgetcharputs

puts() output is appended "time" string


I get very unexpected output from quite simple code

char ch = getchar(), word[100], *p = word;

while (ch != '\n') {
    *(p++) = ch;
    ch = getchar();
}
puts(word);

output of any 17 character input is appended by "time" like

12345678901234567time

if exceeds "time" is overwritten like

1234567890123456789me

Am I doing something wrong?


Solution

  • puts expects a pointer to string. And a string needs to have a terminating null character - \0 - to signify where the string ends.

    But in your case, you did not write the \0 at the end to signify that the string ends there.

    You need to do:

    char ch = getchar(), word[100], *p = word;
    
    /* Also check that you are not writing more than 100 chars */
    int i = 1;
    while(ch != '\n' && i++ < 100){  
        *(p++) = ch; 
        ch = getchar();
    }
    *p = '\0'; /* write the terminaring null character */
    puts(word);
    

    Before, when you were not writing the terminating null character you could not expect anything determinate to print. It could also have been 12345678901234567AnyOtherWord or something.