Search code examples
cinputgetcharputchar

C - Read from input stream, tab as spaces


I'm a bit stuck and am hoping that someone can take a quick look to find what I'm doing wrong. I want to have the tabs count as spaces for output and not tabs. In this case, I'm using 3 spaces = 1 tab. I'm assuming that it may be something to do with how I set up my first while statement since right now it's reading tab as a tab.

int main()
{
  int i, c;
  int N = 3;

  while ((c = getchar ()) != EOF && c != '\n')
  putchar (c);
  while ((c = getchar()) == '\t')
  for (i=1; i<=N; i++) 
    {
      putchar(' ');
    }
  system("Pause");
}

Solution

  • Try this:

    int main()
    {
        int i, c;
        int N = 3;
    
        // exit on Ctrl-C
        while((c = getch()) != 3)
        {
            if(c == '\t')
            {
                for(i=1; i<=N; i++)
                {
                    putchar(' ');
                }
            }
            else if(c == '\r')
            {
                putchar('\r');
                putchar('\n');
            }
            else
            {
                putchar(c);
            }
        }
    }