2012-03-21 91 views
1

C代碼我需要轉換成Java是:將C代碼轉換爲Java代碼:sscanf的

typedef struct 
{ 
    short ih; 
    .... 
} lsettings; 

int ldc_read_parameters(char *param_fnm, lsettings settings, short *image_height) 
{ 
    FILE *fp_param; 
    char line[256]; 
    fp_param = fopen(param_fnm, "r"); 

    if (fp_param) 
    { 
     do fgets(line, 256, fp_param); 
     while (line[0] == '#'); 

     sscanf(line, "%hd", &settings.ih); 
     *image_height = settings.ih; 
    } 
} 

我寫的Java代碼:

class lsettings 
{ 
    public short ih; 
    ..... 
} 

int ldc_read_parameters(String param_fnm, lsettings settings, short image_height[]) 
{ 
    Scanner fp_param;   
    String line; 
    fp_param = new Scanner(new BufferedReader(new FileReader(param_fnm))); 
    if (fp_param.hasNext()) 
    { 

     do 
     { 
      line=fp_param.nextLine(); 

     } while (line.charAt(0) == '#'); 
     Scanner s=new Scanner(line); 
     settings.ih=s.nextShort(); 
     image_height[0] = settings.ih; 
    } 
} 

我是否正確完成轉換或者這裏有什麼不對。我不確定sscanf函數。請幫忙。謝謝。

+1

剛剛嘗試一下呢? – Joey 2012-03-21 07:12:31

+0

當你嘗試時會發現什麼錯誤?你是否嘗試過在調試器中的代碼? – 2012-03-21 08:52:12

回答

1

人的sscanf

The scanf() function reads input from the standard input stream stdin, fscanf() reads input from the stream pointer stream, and sscanf() reads its input from the character string pointed to by str.

h Indicates that the conversion will be one of d, i, o, u, x, X, or n and the next pointer is a pointer to a short int or unsigned short int (rather than int).

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextShort()

雙方的sscanf和nextShort下一個值轉換爲短(在C版本你有符號短)。如果你想要具有相同的精度 - 把它改爲int。在總是簽署的Java中短。

+0

恕我直言'%hd'指的是被簽名的short int。或者我錯過了什麼? – 2012-03-21 11:40:29

+0

'或unsigned short int' - 如果輸入'sscanf(line,「%hd」,&variable);'變量可以是有符號或無符號短符號,它取決於您。在java中short總是有符號的(char是無符號的,但我不知道Scanner是如何解釋它的) – 2012-03-21 11:46:00

+0

但是在'struct lsettings'中它被定義爲'short' – 2012-03-21 11:49:18