将C代码转换为Java代码:sscanf的

问题描述:

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

人的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