2011-08-13 204 views
0

我想在开始和结束时没有空格的打印行。 我不明白为什么从结束删除不起作用。从行尾删除空格

#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; 
    } 
} 

回答

1

看起来像我一个索引错误的错误。如果初始偏移处的字符不是空格或制表符,deleteBlankFromEnd将不执行任何操作;试着找出它是什么?您可能需要以--i

1

您传递给deleteBlankFromEnd函数错误的偏移量,在您的情况下等于输入长度。通过这个您试图访问的内容,实际上是出界这里:

while (line[offset] == ' ' || line[offset] == '\t') 

你最好打电话deleteBlankFromEnd象下面这样:

deleteBlankFromEnd(line, i-1); 

其中第二ARG将指向最后一个字符的字符串。