あなたの質問が「これは私に何を求めているのですか?」元の質問を言い換えることで役立つと思います(同じ質問を別の方法で提起します)。
スペースを含むテキストを入力として受け取り、可能な限りタブを使用して視覚的に同等のテキストを出力として生成するプログラムを作成します。
たとえば、8 文字ごとにタブストップを配置し、スペースを「.」として表示します。タブは「-」として。
input;
".foo:...bar;......#comment"
output;
".foo:-bar;-..#comment"
input;
".......-foo:.....bar;......#comment"
output;
"-foo:-.bar;-...#comment"
タブストップ パラメータ n を変更できるように、つまり 8 以外の n の値を許可するようにプログラムを作成します。
編集私はあなたのコードを見ましたが、必要以上に複雑だと思います。私のアドバイスは、一度に1文字ずつ行うことです。行全体をバッファリングする必要はありません。各文字を読み取るときに列数を維持します ('\n' はゼロにリセットし、'\t' はそれを 1 以上増やし、他の文字はそれを増やします)。スペース (またはタブ) が表示されたら、すぐには何も出力せず、タブ挿入プロセスを開始し、0 個以上のタブを出力してからスペースを出力します (「\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;
}