단원:
12. 포인터
13. 파일 다루기
[프로그래밍 연습 13.8]5개의 물품 정보를 순차적으로 저장하는 프로그램을 작성하라. 정보는 물품 코드, 가격, 재고 개수이며 키보드로 사용자에게 입력을 받는다.
코드:
#include<stdio.h> struct info { int code; float price; int number; }; void writedata(FILE* x, struct info y) { printf("\nitem code:"); scanf("%d", &y.code); fprintf(x, "%d ", y.code); /*scanf 함수로 일차적으로 데이터를 입력받은 다음 그 데이터들을 fprintf함수를 사용하여 파일에 저장한다. 나머지 부분도 동일한 기능*/ printf("\nitem price:"); scanf("%f", &y.price); fprintf(x, "%.2f ", y.price); printf("\nitem number:"); scanf("%d", &y.number); fprintf(x, "%d \n", y.number); } main() { FILE* ptr; struct info item; //item 초기화 item.code = 0; item.price = 0; item.number = 0; char filename[15] = { 0 }; int stop = 0; printf("18101400 전상철\n프로그래밍언어 과제: 5개의 아이템 정보 입력받고 파일 저장 후 가격 총합 계산하기(데이터 입력)\n\n"); printf("생성할 파일 이름 입력: "); scanf("%s", filename); //데이터 입력부 ptr = fopen(filename, "w"); do { writedata(ptr, item); //데이터 입력용 함수 실행 restart: printf("이어서 입력하려면 0을, 입력을 그만두려면 1 입력: "); scanf("%d", &stop); //입력을 언제 그만둘건지 control 변수를 통하여 조절함 if (stop >= 2) { printf("wrong input\n"); //잘못된 입력 감지 goto restart; } } while (stop == 0); fclose(ptr); //파일 닫기 printf("\n\n입력 완료\n"); } |
[프로그래밍 연습 13.9]13.8에서 생성된 파일을 읽어 5개의 물품의 가치 총액을 계산하여 출력하는 프로그램을 작성하라.
코드:
#include<stdio.h> struct info { int code; float price; int number; }; void readdata(FILE* x, struct info y, float* z, long* control) { fscanf(x, "%d %f %d\n", &y.code, &y.price, &y.number); //fscanf 함수를 사용하여 파일에 저장된 데이터 읽어오기. 이때 내부 서식을 파일 생성 프로그램과 같게 함으로서 정상적인 데이터 읽기 가능 if ((y.price * y.number) == 0) { *control = 1; goto end; //가격 데이터가 존재하지 않는 경우(총액이 0) main() 내부의 control 변수에 1을 대입하고 출력은 생략. } *z = *z + (y.price * y.number); //main() 내부의 로컬변수 total에 총액 데이터 저장 fprintf(stdout, "%5d %10.2f %12d\n", y.code, y.price, y.number); //fprintf 함수를 사용하여 콘솔창에 데이터 출력 end: printf("\n"); } main() { FILE* ptr; struct info item; //item 초기화 item.code = 0; item.price = 0; item.number = 0; char filename[15] = { 0 }; long location = 0; long* locationptr; float total = 0; //총액 변수 float* totalptr; //함수 내에서 값을 변경하기위해 포인터 사용 int control = 0; //읽기 제어용 변수 int* controlptr; //함수 내에서 제어변수를 업데이트하기위해 포인터 사용 totalptr = &total; //포인터에 주소값 부여 locationptr = &location; controlptr = &control; printf("18101400 전상철\n프로그래밍언어 과제: 5개의 아이템 정보 입력받고 파일 저장 후 가격 총합 계산하기(데이터 출력)\n\n"); printf("\n읽어들을 파일 이름 입력: "); scanf("%s", filename); printf("\n\n========item table====================\n"); printf("%5s %10s %12s\n", "code", "price", "number"); ptr = fopen(filename, "r"); do { readdata(ptr, item, totalptr, controlptr); } while (control == 0); //출력을 중단해야하는 조건에서 control이 1이 됨으로서 반복문 중단 fclose(ptr); printf("\n물품 가격 총액은 %.2f 입니다.\n", total); } |
문제 소스:
책정보, ANSI C 프로그래밍 : 네이버 책 (naver.com)
ANSI C 프로그래밍
책으로 만나는 새로운 세상
book.naver.com
'프로그래밍 > C,C++' 카테고리의 다른 글
[명품 C++ programming]4,5,6장 실습문제 (0) | 2022.01.06 |
---|---|
[명품 C++ programming]2,3장 실습문제 (0) | 2022.01.06 |
[ANSI C 프로그래밍]10장 프로그래밍 연습 (0) | 2022.01.06 |
[ANSI C 프로그래밍]8,9장 프로그래밍 연습 (0) | 2022.01.06 |
[ANSI C 프로그래밍]5,6,7장 프로그래밍 연습 (0) | 2022.01.06 |