“不可能”的 K&R 练习。
"Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops, say every n columns. Should n be a variable or a symbolic parameter?"
我遇到的问题是,我什至不确定如何正确地执行此操作。我知道这不是很好解释,但这几乎就是这里的问题。我见过的大多数例子都计算了一些空白,并用制表符替换了那些系列,但这不是它的要求,我想我明白它的要求,但目前感觉无法做到这一点。
谁能帮忙:)
编辑:到目前为止我编写的代码 can be found here .
最佳答案
如果您的问题是“这要求我做什么?”我想我可以通过解释原始问题(以不同的方式提出相同的问题)来提供帮助。
编写一个程序,将带空格的文本作为输入,并尽可能使用制表符生成视觉上等效的文本作为输出。
例如,每 8 个字符使用制表位,并将空格显示为“.”和制表符为“-”;
input;
".foo:...bar;......#comment"
output;
".foo:-bar;-..#comment"
input;
".......-foo:.....bar;......#comment"
output;
"-foo:-.bar;-...#comment"
编写程序,使 tabstop 参数 n 可以变化,即允许 n 的值不是 8。准备好证明您将 n 设为常量或变量的决定的合理性。
编辑 我查看了您的代码,我认为它比需要的更复杂。我的建议是一次做一个角色。无需缓冲整行。在读取每个字符时维护列数('\n' 将其重置为零,'\t' 将其增加 1 或更多,其他字符将其递增)。当您看到一个空格(或制表符)时,不要立即发出任何东西,开始您的嵌入过程,发出零个或多个制表符,然后在后面发出空格(在 '\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;
}
关于c - K&R 练习 1-21 - 心理不理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3020031/