2011-08-13 202 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將指向最後一個字符的字符串。