수정해서 다시 질문드립니다(strcmp/txt검색)
큰뫼
질문 제목 :
txt파일의 데이터를 이름(name)으로 검색하여출력하는 프로그램
댓글 보고 힌트를 얻은 후 수정해 다시 올려봅니다.
gets로 입력받은 name과 txt파일의 name을 비교하기 위해 strcmp을 사용하는 것이 맞나요?
구조체 배열와 fp 파일포인터를 연결하기 위해 fgets()를 사용하는 것이 맞나요?
참고로 이름을 입력하면 그 이름에 해당하는 성적이 함게 화면에 출력되어야 합니다.
하지만,Seo로 검색하면 등록되지 않은 이름입니다.라고 한참 출력되다가 멈춤니다.
질문 내용 :
#includestdio.h
#includestring.h
typedef struct student{
int kor,eng,mat,tot;
float avg;
char name[20];
}students;
void main()
{
int i=0;
students data[5]; //5명의 데이터를 담을 배열
char search[20]; //검색할 이름을 받기위한 변수
FILE *fp; //FILE함수 선언
fp=fopen(dap.txt,r); //bin폴더 안에있는 txt파일
if(fp==NULL){ //파일이 있는지 없는지 부터 확인
printf(파일을 찾을 수 없습니다.);
}
printf(검색할 이름을 입력하세요.);
gets(search); //문자열 입력
while(!feof(fp)){ //fp가 파일의 끝을 만날때까지 반복
fgets(data[i].name,sizeof(data),fp);
/*students data[5];5명의 데이터를 담을 구조체 배열과 fp(txt파일 포인터)를 연결해줘야
할 것 같습니다.
fgets를 이용하여 위와 같이 하면 파일의 내용이 구조체배열 속에 순서대로 들어갈 것으로
생각됩니다.*/
if(strcmp(data[i].name, search)==0){
/*gets(search)로 입력받은 이름과 data[i].name을 비교하여
같으면 데이터를 화면에 출력*/
printf(----데이터 출력----\n);
printf(이름: %s\n, data[i].name);
printf(국어: %d\n, data[i].kor);
printf(영어: %d\n, data[i].eng);
printf(수학: %d\n, data[i].mat);
printf(총점: %d\n, data[i].tot);
printf(평균: %f\n, data[i].avg);
i++;
//i가 1씩 증가하며 EOF를 만날때 까지 검색
}
else{
printf(등록되지 않은 이름입니다.\n);
}
fclose(fp); //파일을 닫아줌
}
}
경고메세지: No module definition file specified: using defaults
--data.txt의 내용--
Name | Korea| English | Mathematic | Total | Average |
========================================================
Seo | 100 | 90 | 95| 285| 95.00 |
Kim | 90| 85 | 90 | 265 | 88.33|
Lee | 85 | 95 | 90 | 270 | 90.00 |
Choi | 80| 85 | 80 | 245 | 81.67 |
Park | 90| 95| 90| 275 | 91.67 |
-
꽃가을
fgets() 는 한 줄 끝까지 문자열로 읽습니다..
데이터별로 읽을거면.. fread(), fscanf() 를 사용하거나..
fgets() 는 한 줄 끝까지 문자열로 읽어서 그걸 분석해 사용해야 겠죠.. -
월향
fgets
char *fgets(char *s, int n, FILE *stream);
The function reads characters from the input stream stream and stores them in successive elements of the array beginning at s and continuing until it stores n-1 characters, stores an NL character, or sets