Comment detail

文字列のセンタリング (Nested Flatten)
特にひねりはありません。さらに簡単にできそうな気がします。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *center( char *str, int width, char *out ){
   int len,margin,i=0;
   char *p = out;
   if( !out ){
      return NULL;
   }
   len = strlen(str);
   margin = (abs(width-len)+1)/2;
   if( margin == 0 || len > width ){
      strncpy( p, &str[margin], width );
   }
   else{
      while( i++ < margin ) *p++ = ' ';
      strcpy( p, str );
      p += len;
      while( i++ < width - len + 1 ) *p++ = ' ';
   }
   return out;
}

int main ( int argc, char *argv[] ){
   int n;
   char *out;
   if( argc < 3 ){
      fprintf(stderr, "usage: %s str num\n", argv[0]);
      return EXIT_FAILURE;
   }

   n = atoi( argv[2] );
   if( n <= 0 || (out = malloc( sizeof(char)*n )) == NULL ){
      return EXIT_FAILURE;
   }
   printf("%s#\n", center( argv[1], n, out ) );
   free(out);
   return EXIT_SUCCESS;
}
バグの報告です。
ヌル文字が足りず、変なオマケが後に付きます。
mallocの実装によって気づかないことがあるかもしれません。
私の場合は#が出力されました。丁寧に範囲外の1byteめに'#'をセットしてくれているようです。

Index

Feed

Other

Link

Pathtraq

loading...