The Gateway to Computer Science Excellence
0 votes

#include <stdio.h>

int main ()
  int c;
  while ((c = getchar ()) != EOF)
      putchar (c);
      printf ("*");

  return 0;

when i run this program, the output i get is as


q * w * e * r * t * y *                                                                                                        


i'm not getting how this last "*" is getting printed.

it has something to do with the return of putchar(). so how does putchar() function actually returns. i know that it returns after EOF is reached, so in that case , it won't print anything and printf("*") will get executed. but the thing is, why the last * is getting printed in the next line. is it like putchar() returns and shift the printing pointer to new line?

please clear my doubt.. 



in Programming by Active (3.4k points)
retagged by | 140 views
I think the new line we enter after character input is considered as input and then the last * is printed.
No no. It's not a new line, * is pritned in the next line only .Line spacing is there due to gateoverflow formatting.

I had given just one input qwerty and the output is there as shown.
In this output too there is a * at the end and plus one more at the end of 1st line of output. I'm not getting what's going on.

For I/p : qwerty

O/p will be : q*w*e*r*t*y* only

& If you I/p: qwerty(enter) 

O/p will be: q*w*e*r*t*y*




@Naveen Kumar 3

but how can i make output to get printed without pressing enter?

1 Answer

0 votes

The terminal always buffers the input characters until an EOF or newline character is reached, i.e. the terminal won't send any info to the C program until that happens. Once EOF or newline character is reached, only then the entered info is sent to the C program (along with the EOF/newline char)

For your case, you can test the output by providing the input in a file.

Create input.txt  which contains: qwerty

Assuming you are running windows, run the following to get the output: 

gcc program.c -o output.exe
output.exe < input.txt


by Junior (677 points)

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,833 questions
57,688 answers
107,246 users