我从k&r学习C作为第一语言,我只是想问,如果你认为这个练习是以正确的方式解决的,我知道它可能不像你想的那样完整,但是我想要的意见,所以我知道我正在学习C.
谢谢
/* Exercise 1-22. Write a program to "fold" long input lines into two or
* more shorter lines, after the last non-blank character that occurs
* before then n-th column of input. Make sure your program does something
* intelligent with very long lines, and if there are no blanks or tabs
* before the specified column.
*
* ~svr
*
* [NOTE: Unfinished, but functional in a generic capacity]
* Todo:
* Handling of spaceless lines
* Handling of lines consisting entirely of whitespace
*/
#include <stdio.h>
#define FOLD 25
#define MAX 200
#define NEWLINE '\n'
#define BLANK ' '
#define DELIM 5
#define TAB '\t'
int
main(void)
{
int line = 0,
space = 0,
newls = 0,
i = 0,
c = 0,
j = 0;
char array[MAX] = {0};
while((c = getchar()) != EOF) {
++line;
if(c == NEWLINE)
++newls;
if((FOLD - line) < DELIM) {
if(c == BLANK) {
if(newls > 0) {
c = BLANK;
newls = 0;
}
else
c = NEWLINE;
line = 0;
}
}
array[i++] = c;
}
for(line = 0; line < i; line++) {
if(array[0] == NEWLINE)
;
else
printf("%c", array[line]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我确信你在严谨的轨道上,但有一些可读性指针:
if(array[0] != NEWLINE)
{
printf("%c", array[line]);
}
Run Code Online (Sandbox Code Playgroud)
一个明显的问题是您静态分配“数组”并且在访问它时从不检查索引限制。缓冲区溢出等待发生。事实上,您从未在第一个循环中重置 i 变量,所以我对程序应该如何工作感到有点困惑。看来您在打印自动换行之前将完整的输入存储在内存中?
因此,建议:将两个循环合并在一起,并打印已完成的每一行的输出。然后您可以在下一行中重新使用该数组。
哦,还有更好的变量名和一些注释。我不知道“DELIM”应该做什么。