Here's a possible implementation of the detab program:

#include <stdio.h>

#define TABSTOP 4  // number of columns per tab stop

int main() {
    int c, pos;

    pos = 0;  // current position in the line
    while ((c = getchar()) != EOF) {
        if (c == '\t') {
            // compute the number of spaces needed to reach the next tab stop
            int spaces = TABSTOP - (pos % TABSTOP);
            // output the spaces
            for (int i = 0; i < spaces; i++) {
                putchar(' ');
                pos++;
            }
        } else {
            putchar(c);
            pos++;
            if (c == '\n') {
                pos = 0;  // reset current position at the start of a new line
            }
        }
    }
    return 0;
}

The program reads characters from standard input and outputs them to standard output, replacing tabs with the proper number of spaces. The TABSTOP constant controls the number of columns per tab stop. The program keeps track of the current position in the line (pos), and computes the number of spaces needed to reach the next tab stop when a tab is encountered. It then outputs the required number of spaces, and updates pos accordingly. Other characters are simply output as-is, and pos is incremented accordingly. When a newline character is encountered, pos is reset to 0 to start a new line.

C99 Detab Program: Replace Tabs with Spaces for Fixed Tab Stops

原文地址: https://www.cveoy.top/t/topic/nKML 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录