如果您的问题是“这是要我做什么?”我想我可以通过解释原始问题来提供帮助(以不同的方式提出相同的问题)。
编写一个程序,将带空格的文本作为输入文本,并尽可能使用制表符生成视觉等效文本作为输出。
例如,每 8 个字符有一个制表位,并将空格显示为 '.'和标签为'-';
input;
".foo:...bar;......#comment"
output;
".foo:-bar;-..#comment"
input;
".......-foo:.....bar;......#comment"
output;
"-foo:-.bar;-...#comment"
编写程序,使制表符参数 n 可以变化,即允许 n 的值不为 8。准备好证明您决定将 n 设为常数或变量的合理性。
编辑我看了你的代码,我认为它比它需要的更复杂。我的建议是一次做一个角色。无需缓冲整行。在读取每个字符时保持列计数('\n' 将其重置为零,'\t' 将其增加 1 或更多,其他字符将其增加)。当你看到一个空格(或制表符)时,不要立即发出任何内容,开始你的 entabbing 过程,发出零个或多个制表符,然后是空格(在 '\n' 或非空白字符处,以先到者为准)。
最后一个提示是,状态机可以使这种算法更易于编写、验证、测试和阅读。
编辑 2 为了让 OP 接受我的回答,我现在已经继续并根据我上面提供的提示和我在讨论中的评论自己编写了一个解决方案.
// K&R Exercise 1-21, entab program, for Stackoverflow.com
#include <stdio.h>
#define N 4 // Tabstop value. Todo, make this a variable, allow
// user to modify it using command line
int main()
{
int col=0, base_col=0, entab=0;
// Loop replacing spaces with tabs to the maximum extent
int c=getchar();
while( c != EOF )
{
// Normal state
if( !entab )
{
// If whitespace goto entab state
if( c==' ' || c=='\t' )
{
entab = 1;
base_col = col;
}
// Else emit character
else
putchar(c);
}
// Entab state
else
{
// Trim trailing whitespace
if( c == '\n' )
{
entab = 0;
putchar( '\n' );
}
// If not whitespace, exit entab state
else if( c!=' ' && c!='\t' )
{
entab = 0;
// Emit tabs to get close to current column position
// eg base_col=1, N=4, col=10
// base_col + 3 = 4 (1st time thru loop)
// base_col + 4 = 8 (2nd time thru loop)
while( (base_col + (N-base_col%N)) <= col )
{
base_col += (N-base_col%N);
putchar( '\t' );
}
// Emit spaces to close onto current column position
// eg base_col=1, N=4, col=10
// base_col -> 8, and two tabs emitted above
// base_col + 1 = 9 (1st time thru this loop)
// base_col + 1 = 10 (2nd time thru this loop)
while( (base_col + 1) <= col )
{
base_col++;
putchar( ' ' );
}
// Emit buffered character after tabs and spaces
putchar( c );
}
}
// Update current column position for either state
if( c == '\t' )
col += (N - col%N); // eg col=1, N=4, col+=3
else if( c == '\n' )
col=0;
else
col++;
// End loop
c = getchar();
}
return 0;
}