2010-01-08 24 views
-2
#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 

#define TAB_STOP 8 
/* replaces tabs from input with the proper amount of blank spots */ 
int Detab() 
{ 
    int c, x; 
    int column; 
    x = column = 0; 

    while((c=getchar())!=EOF) 
    { 
     if(c == '\n') /* reseting counter if newline */ 
     { 
      putchar(c); 
      return 1; 
     } 
     else if(c!='\t') /* column counts places to tab spot */ 
     { 
      putchar(c); 
      column++; 

      if(column == TAB_STOP) 
      column = 0; 
     } 
     else /* tab */ 
     { 
      for(x=0; x<TAB_STOP - column; x++) 
      putchar('_'); 

      column = 0; 
     } 
    } 
    return 0; 
} 

#define MAX_ARGUMENTS 100 
int main(int argc, char *argv[]) 
{ 
    int i, val = 0; 
    int nums[MAX_ARGUMENTS]; 
    int x = 0; 

    for(i = 1; i < argc; i++) { 

      while(isdigit(*argv[i])) { 
      val = val * 10 + *argv[i] - '0'; 
      *++argv[i]; 
      } 

      if(x > MAX_ARGUMENTS - 1) 
       return 0; 

      nums[x++] = val; 
      nums[x] = '\0'; 
      val = 0; 
    } 

    while(Detab(nums)); 

    printf("Press any key to continue.\n"); 
    getchar(); 
    return 0; 
} 

在主要我把所有的參數(數字)在nums數組內,然後將它傳遞給detab。所以現在我感興趣什麼是編輯detab的聰明方式,所以它的工作原理。我仍然試圖找出一個工作的僞代碼,但我真的不知道。如何修改detab接受參數列表

我因子評分它應該工作的方式是:如果 參數是5,8,10,則內側第一4個字符的標籤導致5位,在5 - 第七炭導致POS 8等 In的情況下換行,爭論從頭再次開始。

+0

我在這裏沒有看到具體問題。一般來說,這裏的人不會做普通的「修復代碼」的事情。他們回答具體的技術問題。 – bmargulies 2010-01-08 00:44:44

+0

你的問題是參數解析還是detab函數本身? – 2010-01-08 00:46:40

+0

工具:這將有助於澄清問題,例如「我如何編寫Detab以便它包含參數列表?它的原型是什麼?」你的上一個問題有很多信息不適用於分散注意力。 – 2010-01-08 00:55:05

回答

0

最常見的方式是有Detab接受一個指針(它指向一個數組中的元素),並且陣列的長度:

int Detab(int* data, int len); // access data[0] through data[len - 1] 

呼叫它像這樣:

void example() { 
    int array[] = {5, 8, 10}; 
    Detab(array, 3); 
    // or: 
    Detab(array, sizeof array/sizeof *array); // second parameter evaluates to 3 
               // without using a magic constant 
} 

下面是一些僞代碼,擴大標籤:

def expandtabs_in_line(line, tabstops, default, space): 
    result = "" 
    for c in line: 
    if c != "\t": 
     result += c 
    else: 
     for stop in tabstops: 
     if stop > len(result): 
      result += space * (stop - len(result)) 
      break 
     else: 
     result += space * (default - (len(result) % default)) 
    return result 

def expandtabs(lines, tabstops=[], default=8): 
    for line in lines: 
    yield expandtabs_in_line(line, tabstops, default, " ") 

嘗試一下在codepad

+0

大小,忘了那個......謝謝! – Tool 2010-01-08 01:23:38

+0

你可以把它翻譯成C嗎?我從來沒有真正在Python工作,我真的不能翻譯...該代碼也使用getline函數,對吧?另外,len(結果)是什麼? – Tool 2010-01-08 02:21:01

+0

你問了僞代碼,「Python是可執行的僞代碼」,所以我用它。 :)這段代碼需要一行數組並迭代它('for .. in ..'),轉換每行(在單獨的函數中)並返回它(yield是一種特殊的返回類型)。 'len()'是長度函數,'len(result)'是結果的當前長度。 – 2010-01-08 02:29:56