【发布时间】:2011-10-09 21:19:44
【问题描述】:
C编程语言练习1-22如下:
编写一个程序,将较长的输入行“折叠”成两个或多个较短的行 在 n-th 之前出现的最后一个非空白字符之后的行 输入列。确保你的程序做一些智能的事情 行很长,并且如果在前面没有空格或制表符 指定的列。
这是代码:
#include <ctype.h>
#include <stdio.h>
#define MAXLINE 500
#define FOLD_LENGTH 15
/* _getline: read a line into s, return length */
size_t _getline(char s[], int lim)
{
int c;
size_t i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
int main()
{
int c;
char line[MAXLINE];
char temp;
unsigned last_space_idx = 0, i, offset = 0;
while (_getline(line, MAXLINE) != 0) {
for (i = 0; line[offset+i] != '\0'; i++) {
if (i == FOLD_LENGTH) {
temp = line[offset+last_space_idx];
line[offset+last_space_idx] = '\0';
printf("%s\n", line+offset);
line[offset+last_space_idx] = temp;
offset = last_space_idx;
i = 0;
continue;
}
if (isspace(line[offset+i])) {
last_space_idx = offset+i;
}
}
printf("%s\n", line+offset);
}
return 0;
}
这是我正在使用的示例输入:
Penny Lane 在我的耳朵和我的眼睛里 在下面 郊区的蓝天这是我得到的输出:
便士巷是 在我的耳朵和我的眼睛里 在我眼里 眼睛 眼睛 眼睛这里有什么错误?我真的不知道。
【问题讨论】:
-
我必须问:你是在使用 ANSI 颜色代码将“Penny Lane”变成浅蓝色吗?那真的可以把事情搞砸了。