Search code examples
cgetchar

Getchar, switching in C


I am trying to prepend numbers to the "putchar" portion, but because getchar is grabbing a character at a time, the output for "hi" turns to 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;
  }
}

All help would be appreciated. I am trying to make the output:

1 hi 
2 hello

and not

hi 1
hello 2 

Solution

  • This seems to work:

    #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;
    }
    

    Output when run on its own source code (./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      }