我正在尝试在开始和结束时没有空格的打印行。 我无法弄清楚为什么从末端删除不起作用。
#include <stdio.h>
#define MAX_LINE_LENGTH 1000
#define LINE_BEGIN 0
#define LINE_MIDDLE 1
#define INBLANK 2
void deleteBlankFromEnd(char line[], int offset);
void deleteLine(char line[], int offset);
main()
{
int c, i, status ;
i = status = 0;
char line[MAX_LINE_LENGTH];
while((c = getchar()) != EOF) {
if (c == ' ' || c == '\t') {
if (status == LINE_MIDDLE || status == INBLANK) {
line[i++] = c;
if (status == LINE_MIDDLE)
status = INBLANK;
}
} else if (c == '\n') {
if (status > 0) {
if (status == INBLANK) {
printf("Line length = %d ", i);
deleteBlankFromEnd(line, i);
}
printf("%s", line);
printf("End\n");
deleteLine(line, i);
}
i = 0;
status = LINE_BEGIN;
} else {
line[i++] = c;
status = LINE_MIDDLE;
}
}
}
void deleteBlankFromEnd(char line[], int offset) {
while (line[offset] == ' ' || line[offset] == '\t') {
line[offset--] = 0;
}
printf("Line length = %d ", offset);
}
void deleteLine(char line[], int offset) {
while (offset >= 0) {
line[offset--] = 0;
}
}
答案 0 :(得分:1)
对我来说,看起来像一个一个一个索引错误。如果初始偏移处的字符不是空格或制表符,则deleteBlankFromEnd将不执行任何操作;试着找出它是什么?您可能需要从--i
开始答案 1 :(得分:1)
您传递给deleteBlankFromEnd
函数错误的偏移量,在您的情况下等于输入的长度。通过这个你试图访问实际上超出界限的内容:
while (line[offset] == ' ' || line[offset] == '\t')
你最好像下面这样调用deleteBlankFromEnd:
deleteBlankFromEnd(line, i-1);
其中第二个arg将指向字符串中的最后一个字符。