KU COSE101 2016기말고사 3번 문제

2 minute read

             
2016 기출 1번 2번 3번 4번 5번  
2017 기출 1번 2번 3번 4번 5번  
2018 기출 1번 2번 3번 4번 5번 6번

문제에 명확한 설명이 부족하여 코드를 일부 보강하였습니다.

strstr, strcat을 사용하는 이기 때문에 안배우셔서 스킵하셔도 됩니다.

topuniv.txt 파일은 아래와 같이 세계 우수대학에 대한 정보를 담고 있다.

...
several cities in Korea has university and college campuses in
downtown. The one located in Anam-dong is Korea University
established in 1905.
...
ranked 104th in the world and 19th in the Asia rankings, Korea
University has a student body of nearly 37,500, and, of its faculty of
1,500, over 95% hold a PhD or equivalent within
...

(a) topuniv.txt에서 “Korea University” 라는 단어가 포함된 라인만을 골라서 그 위치와 내용을 output1.txt라는 파일에 새로 저장하려고 한다. 이 함수를 완성하라. (<string.h>에서 제공하는 함수를 include한다면 사용할 수 있으며, 대소문자는 다른 것으로 간주함. 예를 들어 “korea university”는 “Korea University”와 다른 것으로 간주하여 찾지 않음. 또 “Korea”와 “University” 사이에는 단 하나의 공백만이 있어야 함)

void find_single_line(char* input_file, char* output_file) {
  //fill the function
  
  //int ln : line number at which Korea University is found
  //char line[] : string buffer containing the line
  fprintf(out, "At %d: %s\n", ln, line);
  //complete the function
  
}

int main() {
  char input_file[] = "topuniv.txt"
  char output1_file[] = "output1.txt"
  find_single_line(input_file, output1_file);
  return 0;
}

(b) 불행하게도 위 함수는 “Korea University”라는 단어가 연속되지만 두 줄에 나뉘어 나타나는 경우 출력 파일에 포함되지 않는다. 두 단어가 연속되어 다른 줄에 나타나는 경우를 처리하는 함수를 완성하라. 출력은 output2.txt 파일에 저장하기로 한다. (기타 가정은 위 문제와 같음)

void find_divided_lines(char* input_file, char* output_file) {
  //fill the function
  
  //int ln : line number at which Korea is found
  //char line[] : string buffer containing the line
  fprintf(out, "At %d divided\n", ln);
  //complete the function
  
}

int main() {
  char input_file[] = "topuniv.txt"
  char output1_file[] = "output1.txt"
  char output2_file[] = "output2.txt"
  find_single_line(input_file, output1_file);
  find_divided_lines(input_file, output2_file);
  return 0;
}

예시풀이
void find_single_line(char* input_file, char* output_file) {
	FILE *fp = fopen(input_file, "r");
	FILE *out = fopen(output_file, "w");
	int ln = 0;
	char line[100];
	while(fgets(line, 100, fp) != NULL) {
		ln++;
		if(strstr(line, "Korea University")) {
			fprintf(out, "At %d: %s\n", ln, line);
		}
	}
	fclose(fp);
	fclose(out);
}

void find_divided_lines(char* input_file, char* output_file) {
	char line[200];
	char prevline[200];
	FILE *fp = fopen(input_file, "r");
	FILE *out = fopen(output_file, "w");
	
	int ln = 0;
	prevline[0] = 0;
	
	while(fgets(line, 100, fp) != NULL){
		ln++;
		strcat(prevline, line);
		if(strstr(prevline, "Korea\nUniversity")){
			fprintf(out, "At %d divided\n",ln-1);
		}
		strcpy(prevline, line);
	}
	fclose(fp);
	fclose(out);
}

Comments