dポイントプレゼントキャンペーン実施中!

c言語でデータの指定列の度数分布をつくろうとしています。

以下のように1列のデータに対してはプログラムを組むことができます。


#include<stdio.h>
#include<stdlib.h>

#define UPPERBOUND 2.0
#define LOWERBOUND -2.0
#define RANGE 0.1

int main(int argc, char* argv[]){
int i;
FILE *fp;
FILE *fp2;
char str[256];

if(argc != 2 && argc != 3){
printf("***usage: %s <datafilename>\n", argv[0]);
exit(-1);
}

if((fp = fopen(argv[1], "r")) == NULL){
printf("can't open file\n");
exit(-1);
}

if(argc == 3){
if((fp2 = fopen(argv[2], "w")) == NULL){
printf("can't open outputfile\n");
exit(-1);
}
}

int tablesize = (UPPERBOUND-LOWERBOUND)/RANGE;
int table[tablesize];
for(i=0; i<tablesize; i++){
table[i] = 0;
}

while((fgets(str, 256, fp)) != NULL){
double dbl = atof(str);

if(!(dbl < LOWERBOUND || dbl > UPPERBOUND)){
int n = (dbl-LOWERBOUND)/RANGE;
table[n]++;
}
}

for(i=0; i<tablesize; i++){
printf("%lf~%lf\t: %d\n", LOWERBOUND+(i*RANGE), LOWERBOUND+((i+1)*RANGE), table[i]);

if(argc == 3){
fprintf(fp2, "%lf~%lf\t: %d\n", LOWERBOUND+(i*RANGE), LOWERBOUND+((i+1)*RANGE), table[i]);
}
}

return 0;
}

そこで複数列のデータに対して、例えば10列100行のデータに対して6列目だけを見たいときはどうすればできますでしょうか?

A 回答 (1件)

やることは一緒ですよ


ただ fgetsで一行取得した中から 6列目をどう見つけるかだけだと思います

データの区切りが『,』であるなら

char* FindData( char* str, int n )
{
  char *ptr = NULL;
  if ( n > 0 ) {
    if ( NULL != (ptr = strcchr( str, ',' )) ) {
      --n;
      ptr++; // 最初の『,』をスキップ
      while( n-- ) {
        ptr = strchr( ptr, ',' );
        if ( ptr == NULL )
          break;
        ptr++; // 見つけた『,』をスキップ
      }
    }
  } else if ( n == 0 ) {
    ptr = str;
  }
  return ptr;
}

といった関数を用意して

while((fgets(str, 256, fp)) != NULL){
  // 1列目が0としているので 6列目なら5を引数にします
  char *p = FindData( str, 5 );
  if ( p != NULL ) {
    double dbl = atof(str);

    if(!(dbl < LOWERBOUND || dbl > UPPERBOUND)){
      int n = (dbl-LOWERBOUND)/RANGE;
      table[n]++;
    }
  }
}
といった具合でしょう
    • good
    • 0
この回答へのお礼

ご丁寧に教えていただきありがとうございます。

お礼日時:2010/10/05 14:47

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!