본문 바로가기
IT/프로그래밍

C언어 본색 파트3 Chapter 3 연습문제 솔루션

by nutrient 2021. 5. 31.
728x90
728x170

 

 

1번

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

int main(void){
	char fileName[] = "99.txt";
	int i, j;
	FILE* outFile = NULL;


	//출력파일 생성
	printf("출력파일 99.txt 생성\n");
	if( (outFile = fopen(fileName, "wt")) == NULL ){
		exit(-1);
	}

	
	//구구단 파일에 출력
	printf("출력파일 99.txt에 구구단 출력 시작\n");
	for(i = 1; i <= 9; i++){
		for(j = 1; j <= 9 ; j++){
			fprintf(outFile, "%d * %d = %d\n", i, j, i*j);
		}
		fprintf(outFile, "\n");
	}
	printf("출력파일 99.txt에 구구단 출력 완료\n");

	//파일 출력이 끝나고 파일 닫음
	printf("출력파일 99.txt 닫음\n");
	fclose(outFile);
	return 0;
}
/*해설
outFile 파일포인터 변수에 fopen()함수로 출력할 파일을 생성한다.
출력파일 생성시 "wt"옵션으로 생성하여, 텍스트 출력 모드로 생성한다.
구구단을 화면에 출력하는 것과 동일하게 작성하되, fprintf()함수로 파일포인터 outFile에 출력한다.
구구단 출력이 끝난 후 fclose()함수로 파일포인터 outFile을 닫는다.
*/

 

2번

//
//  main.c
//  testProject
//
//  Created by Sung Tae Ryu on 12. 2. 26..
//  Copyright (c) 2012년 thinksquare. All rights reserved.
//
#include <stdio.h>

int main() { 
    int i, j, r;
    
    FILE* fp;
    
    fp = fopen("99.txt", "w");
    
    for (i=2; i<=9; i++) {
        fputc((char)(i+48), fp);
        fputs("단\n", fp);
        
        for (j=1; j<=9; j++) {
            fputc((i+48), fp);
            fputc('*', fp);
            fputc((j+48), fp);
            fputc('=', fp);
            
            r = i*j;
            
            fputc((((int)(r/10))+48), fp);
            fputc((r%10+48), fp);
            fputc('\n', fp);
        }
        fputc('\n', fp);
    }

    return 0;
}


/*
 
 fputc를 사용하게 되면 출력을 위해 ASCII코드 값을 계산하여 하나씩 출력해줘야하므로 많은 불편함이 있다.
 또한 decimal처리를 수동으로 해줘야하기 때문에 코드의 양이 많이 늘어나게 된다. fprintf의 경우에는
 %d와 같이 int형을 바로 사용할 수 있는 지시자를 사용할 수 있기 때문에 출력하는 것이 훨씬 간편하다. 
 
*/

 

3번

//
//  main.c
//  testProject
//
//  Created by Sung Tae Ryu on 12. 2. 26..
//  Copyright (c) 2012년 thinksquare. All rights reserved.
//

#include <stdio.h>


int main()
{
    char array1[50];
    char array2[50];
    int i, j, w;
    FILE* fp1;
    FILE* fp2;
    
    char input;
    
    fp1 = fopen("source.txt", "r");
    fp2 = fopen("dest.txt", "w");
    
    for (i=0; i<50; i++) {
        array1[i] = 0;
        array2[i] = 0;
    }
    
    for(i=0; input != EOF; i++) {
        input = fgetc(fp1);
        
        array1[i] = input;
    }
    
    array1[i-1] = '\0';
    
    
    w = 0;
    
    for(j=0; j<i-1; j++) {
        if((j%5 == 0 && j >= 5)) {
            w += 10;
            
            if(i-2-j < 5) {
                w -= 4-(i-2-j);
            } 
            
            printf("-------------\n");
        }
        
        array2[j] = array1[4+w-j];
        printf("[%d/%d] <- %c\n", j, i-2, array1[4+w-j]);
    }
    
    printf("%s\n", array1);
    printf("%s", array2);
    
    fprintf(fp2, "%s", array2);
    
    fclose(fp1);
    fclose(fp2);
    return 0;
}


/*

 파일을 fgetc를 이용하여 파일의 끝에 도달할 때까지 읽고, array1에 저장합니다.
 파일에서 읽은 문자열을 사용하기 위해 마지막에 널문자를 넣어줍니다.
 이후 점화식에 따라 문자열을 5바이트마다 뒤집어 array2에 저장합니다.
 
*/

 

4-6번

//
//  main.c
//  testProject
//
//  Created by Sung Tae Ryu on 12. 2. 26..
//  Copyright (c) 2012년 thinksquare. All rights reserved.
//
#include <stdio.h>
#include <string.h>


struct student_score
{
    int no;
    char name[10];
    float num1, num2, num3, total;
};

int main() { 
    int i;
    int search = 0;
    
    struct student_score s1[7] = {
        {1, "박지성", 90.2, 90.1, 88.8}, 
        {2, "이청용", 89.1, 88.5, 90.2}, 
        {3, "박주영", 92.1, 87.1, 90.1}, 
        {4, "기성용", 85.3, 86.2, 95.1}, 
        {5, "구자철", 88.2, 86.3, 91.1}, 
        {6, "지소연", 98.2, 90.1, 93.5}, 
        {7, "전가을", 93.3, 95.5, 91.2}
    };
    
    struct student_score str[7];
    
    FILE* fp1;
    FILE* fp2;
    
    fp1 = fopen("score.txt", "w");
    
    for(i=0; i<7; i++) {
        fprintf(fp1, "%d. %s %.1f %.1f %.1f \n", s1[i].no, s1[i].name, s1[i].num1, s1[i].num2, s1[i].num3);
    }
    
    fclose(fp1);
    
    fp1 = fopen("score.txt", "r");
    fp2 = fopen("score1.txt", "w");
    
    for(i=0; i<7; i++)
    {
        fscanf(fp1, "%d. %s %f %f %f ", &str[i].no, str[i].name, &str[i].num1, &str[i].num2, &str[i].num3);
        str[i].total=str[i].num1+str[i].num2+str[i].num3;
        fprintf(fp2, "%d. %s %.1f %.1f %.1f total : %.1f \n", str[i].no, str[i].name, str[i].num1, str[i].num2, str[i].num3, str[i].total);
    }
    
    fprintf(stdout, "input number : ");
    fscanf(stdin, "%d", &search);
    
    for(i=0; i<7; i++) {
        if(i+1 == search) {
            fprintf(stdout, "name : %s  total : %.1f \n", str[i].name, str[i].total);
        }
        else
            continue;
        
    }
    
    fseek(fp1,  0, SEEK_END);
    fprintf(stdout, "score size : %d byte \n", ftell(fp1));
    fclose(fp1);
    fclose(fp2);
    return 0;
}


/*

 먼저 파일을 따로 작성하지 않고 소스 코드에서 score.txt를 작성하여 다시 읽어드립니다.
 총점을 계산하고 이를 메모리 상에 저장해놓고 있으며, score1.txt를 만들어 총점까지 합친 결과를 저장합니다.
 이후 선수의 번호를 입력받아, 해당 선수의 총점과 이름이 검색되고 출력되며, score.txt의 총 파일 크기를 구하여 알려줍니다.
 여기서 주의할 점은 소수점 데이터의 활용입니다. 소수점 하나까지만 출력하기 위해 "%.1f"를 사용했지만, fscanf를 이용할 때는
 "%f"만을 사용한다는 점을 주의하세요.
 
*/

 

7번

//
//  main.c
//  testProject
//
//  Created by Sung Tae Ryu on 12. 2. 26..
//  Copyright (c) 2012년 thinksquare. All rights reserved.
//
#include <stdio.h>
#include <string.h>


struct student_score
{
    char no[10];
    char name[10];
    int middle, final, attendance, homework, total;
    char* grade;
};

int main() { 
    int exit = 0;
    
    struct student_score student_temp;
    
    FILE* fp1;
    
    fp1 = fopen("score.txt", "w");
    
    while (!exit) {
        printf("학번:");
        scanf("%s", student_temp.no);
        printf("이름:");
        scanf("%s", student_temp.name);
        printf("중간고사:");
        scanf("%d", &student_temp.middle);
        printf("기말고사:");
        scanf("%d", &student_temp.final);
        printf("출석:");
        scanf("%d", &student_temp.attendance);
        printf("과제:");
        scanf("%d", &student_temp.homework);
        
        student_temp.total = student_temp.middle + student_temp.final + student_temp.attendance + student_temp.homework;
        
        if (student_temp.total >= 95) {
            student_temp.grade = "A+";
        }
        else if (student_temp.total >= 90) {
            student_temp.grade = "A";
        }
        else if (student_temp.total >= 85) {
            student_temp.grade = "B+";
        }
        else if (student_temp.total >= 80) {
            student_temp.grade = "B";
        }
        else if (student_temp.total >= 75) {
            student_temp.grade = "C+";
        }
        else if (student_temp.total >= 70) {
            student_temp.grade = "C";
        }
        else {
            student_temp.grade = "F";
        }
        
        
        
        fprintf(fp1, "%s %s %2d %2d %2d %2d %3d %s \n", student_temp.no, student_temp.name, student_temp.middle, student_temp.final, student_temp.attendance, student_temp.homework, student_temp.total, student_temp.grade);
        
        printf("학생 정보를 파일에 저장하였습니다.\n");
        
        printf("그만 두시겠습니까? (네:1, 아니요:0) : ");
        scanf("%d", &exit);
    }
    
    fclose(fp1);

    return 0;
}


/*
 
 데이터를 체계적으로 저장하기 위해 구조체를 작성하였습니다.
 scanf를 이용하여 데이터를 구조체에 저장하고 총점과 학점을 계산한 뒤 이를 fprintf를 이용하여 파일에 기록합니다.
 
 */
728x90
그리드형

댓글