hibari さんが書きました:CSVファイルを読み込んで一つのクラスごと構造体のリストに入れたいのですが、うまくいきません。
下記が読み込みたいCSVファイルの一部です。
上記のCSVファイルみたいになると方法が分かりません。
いい方法はないでしょうか?
コード:
#include <stdio.h>
#include <string.h>
#define CVSBUFFSIZE 1024
typedef struct {
char stu_num[16]; /* 出席番号 */
char stu_name[16]; /* 生徒名 */
char stu_sei[16]; /* 性別 */
} Student;
typedef struct {
int student_id[35];
char cla_name[16]; /* クラス名 */
char cla_tea[16]; /* 担任名 */
char cla_num[16]; /* クラス人数 */
} Class;
Class class[30];
Student student[200];
int main( void )
{
int curr_class=0;
int curr_student=0;
int student_wclass;
int class_defined = 0;
char buff[CVSBUFFSIZE];
char buff2[40];
FILE *rfp;
int nenn, kumi, ninzu;
char *ptannin;
int sekiban;
char *seitomei, *seibetu;
char *wptr;
rfp = fopen( "class.cvs", "r" );
do {
if( fgets( buff, CVSBUFFSIZE, rfp ) ) {
if( '\n' == buff[0] || '\n' == buff[1] ) continue;
if( 3 == sscanf( buff, "%d-%d,%s", &nenn, &kumi, buff2 ) ) {
wptr = strchr( buff2, ',' );
*wptr = '\0';
if( class_defined ) ++curr_class;
student_wclass=0;
sprintf( class[curr_class].cla_name, "%d-%d", nenn, kumi );
strcpy( class[curr_class].cla_tea, buff2 );
strcpy( class[curr_class].cla_num, wptr+1 );
class_defined = 1;
printf( "Debug Read class No: %d Name:%s\n", curr_class, class[curr_class].cla_name );
continue;
}
if( 2 == sscanf( buff, "%d,%s", &sekiban, buff2 ) ) {
wptr = strchr( buff2, ',' );
*wptr = '\0';
sprintf( student[curr_student].stu_num, "%d", sekiban );
strcpy( student[curr_student].stu_name, buff2 );
strcpy( student[curr_student].stu_sei, wptr+1 );
class[curr_class].student_id[student_wclass] = curr_student;
++ student_wclass;
++ curr_student;
printf( "Debug Read student No: %d Name:%s\n", curr_student, student[curr_student].stu_name );
continue;
}
}
} while( ! feof( rfp ) );
return 0;
}
下記をポインタにしてmalloc/reallocすればクラス数や合計生徒数などをメモリの許す限り無限に増やせます。
Class class[30];
Student student[200];
int student_id[35]; /*1クラス最大35名*/
} Class;