0

我正在尝试将数字添加到“putchar”部分,但由于 getchar 一次抓取一个字符,“hi”的输出变为1 h 2 i

int linecount = 1;
int numberflag = 1;


while (1){
  int input = getchar(); // use int to make sure var input is big enough to hold EOF plus any other char


  switch (input) {
    case EOF:
      exit(-1);

    default:
      if (numberflag){
        printf("\t%d\t", linecount);
        linecount++;
      }
      putchar(input);
      break;
  }
}

所有帮助将不胜感激。我正在尝试输出:

1 hi 
2 hello

并不是

hi 1
hello 2 
4

1 回答 1

3

这似乎有效:

#include <stdio.h>

int main(void)
{
    int linecount = 1;
    int numberflag = 1;
    int sol = 1;
    int c;

    while ((c = getchar()) != EOF)
    {
        if (numberflag && sol)
        {
            printf("\t%d\t", linecount++);
            sol = 0;
        }
        if (c == '\n')
            sol = 1;
        putchar(c);
    }
    return 0;
}

在自己的源代码上运行时的输出 ( ./sol < sol.c):

        1       #include <stdio.h>
        2
        3       int main(void)
        4       {
        5           int linecount = 1;
        6           int numberflag = 1;
        7           int sol = 1;
        8           int c;
        9
        10          while ((c = getchar()) != EOF)
        11          {
        12              if (numberflag && sol)
        13              {
        14                  printf("\t%d\t", linecount++);
        15                  sol = 0;
        16              }
        17              if (c == '\n')
        18                  sol = 1;
        19              putchar(c);
        20          }
        21          return 0;
        22      }
于 2013-04-16T20:51:14.510 回答