开发者

printing a line number for each line entered in standard input

what i want to do is print a number for each line entered. eg when a user enters "jaguar", the program will output:

1 jaguar

and if the user then enters "lion" the output should be:

2 lion.

In other words the screen will be looking like this:

jaguar 1 jaguar lion 2 lion leopard 3 leopard...

Sounds easy yes. Here is my code which is printing things wrongly and i dont understand how and why....

int main (int开发者_运维问答 argc, const char * argv[])
{
  int lineNum = 0;
  char c;
  while(  (c= fgetc(stdin) )  != EOF)          
  {
    if(c == '\n')
    {
      lineNum++;
      printf("\n %i", lineNum);
    }
    else
    {
      fputc(c, stdout);
    }
  }
  //return 0;
}


Does this work for you ?

char buffer[256];
int i = 1;

while (fgets(buffer, sizeof(buffer), stdin)) {
    printf("%d %s", i, buffer);
    i++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜