텍스트 파일에서 첫번째 짧은 단어와 두번째 짧은단어, 그리고 첫번째 긴 단어와 두번째 긴 단어를 출력하는 예제...
글쓴이: quarterhorse / 작성시간: 토, 2012/12/15 - 9:28오후
안녕하세요, 다름이 아니라, 예제를 연습하다가 질문 드립니다.
텍스트 파일에서 첫번째 짧은 단어와 두번째 짧은단어, 그리고 첫번째 긴 단어와 두번째 긴 단어를 출력하는 예제가 있는데요,
첫번째 짧은 단어와 두번째 짧은 단어를 출력해주는것은 성공했는데,
첫번째 긴 단어와 두번째 긴 단어를 출력하는것을 실패했습니다.
실제로 콘솔에서 실행해보면 shortest, second shortest만 출력됩니다... ㅠㅠ
아래는 제가 짜본 코드입니다.
#include <stdio.h>
#include <string.h>
#define MAXLINE 100
void copy(char from[], char to[]);
char line[MAXLINE];
char shortest[MAXLINE];
char secshortest[MAXLINE];
char longest[MAXLINE];
char seclongest[MAXLINE];
main()
{
int len,min,secmin,max,secmax;
min = 99999;
secmin = 99999;
max = 0;
secmax = 0;
FILE *fp;
fp= fopen("/home/quarterhorse/program/twoshortlong/text.txt","r");
if(fp == NULL)
{
printf("File open for reading Fail! \n");
return 0;
}
while(1){
if(fgets(line,MAXLINE,fp) == NULL){
if(min < 99999)
printf("shortest : %s\n", shortest);
if(secmin < 99999)
printf("second shortest : %s\n", secshortest);
if(max > 0)
printf("longest : %s\n",longest);
if(secmax > 0)
printf("secong longest : %s\n",seclongest);
return 0;
}
len = strlen(line);
if(len<min)
{
secmin=min;
min=len;
copy(shortest,secshortest);
copy(line,shortest);
}
else if(len<secmin)
{
secmin=len;
copy(line,secshortest);
}
if(len>max)
{
secmax=max;
max=len;
copy(longest,seclongest);
}
} //end of while
}//end of main
void copy(char from[],char to[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}생각대로라면 짧은거 판별해주는 로직은 잘못되있는거 같진 않은데, 긴거 판별해 주는 로직이 감이 안잡힙니다...
어떻게 수정해야 첫번째 긴 단어와 두번째 긴 단어를 출력할 수 있을까요.... ㅠㅠ
도움 주시면 정말 감사드리겠습니다....
Forums:


두 논리가 서로 다른 것 같진 않군요.
#include <stdio.h> #include <string.h> #define MAXLINE 100 void copy(const char from[], char to[]); char line[MAXLINE]; char shortest[MAXLINE]; char secshortest[MAXLINE]; char longest[MAXLINE]; char seclongest[MAXLINE]; int main(void) { int len; int min=99999, secmin=99999; int max=0, secmax=0; // 제 스타일입니다만, // 같은 int 타입의 변수를 선언하더라도 // 쓰임새에 따라 선언을 분리해주면 // 보기 좋다는 생각에 이렇게 합니다. /* 요즘 표준은 블록 중간에 변수를 선언해도 괜찮다는 소리를 듣기는 했습니다만, C에서는 되도록 블록 중간에 변수를 선언하지 않는 게 좋다고 생각합니다. (저는 C++로 코드를 짤 때도 변수 선언은 위쪽에만 둡니다.) min = 99999; secmin = 99999; max = 0; secmax = 0; */ // 파일 포인터 변수를 선언하는 부분이니, // 예전 표준이라면 컴파일 오류를 일으키겠죠. // min, secmin 등 값 대입 부분이 선언 이전에 나타났으니까요. FILE *fp; // 전 경로 같은 부분은 매번 이렇게 선언을 해주게 되더군요. const char path[] = "test.txt"; fp = fopen(path, "r"); if (!fp) // if(fp == NULL) { // 이렇게도 쓸 수 있다고 알아두시는 게 좋을 것 같습니다. printf("File open for reading Fail! \n"); return 0; } // 제가 짠 논리입니다. while (fgets(line, MAXLINE, fp)) { // fgets(line, MAXLINE, fp)!=0) len = strlen(line); if (line[len-1]=='\n') { line[len-1] = 0; --len; } if (len<min) { secmin = min; min = len; strcpy(secshortest, shortest); strcpy(shortest, line); } else if (max<len) { secmax = max; max = len; strcpy(seclongest, longest); strcpy(longest, line); } } // 파일을 모두 읽었으므로 닫음 fclose(fp); printf("shortest : %s\n", shortest); printf("second shortest : %s\n", secshortest); printf("longest : %s\n",longest); printf("second longest : %s\n", seclongest); return 0; }//end of main // 내용이 변경되지 않는 포인터는 const를 이용해, // 함수의 원형만으로 그 내용이 변경되지 않음을 // 바로 알 수 있게 할 수 있습니다. void copy(const char from[], char to[]) { // 이렇게 써볼 수도 있겠군요. while ((*to++ = *from++)) ; // 사실 표준함수 strcpy를 쓰셔도 됐습니다. /* int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; */ }두 문장의 길이가 같은 경우 등의 예외 처리는 안 되어있습니다.
저는 이렇게 생각했습니다.
확실히...
더욱 깔끔하게 이런식으로도 나올수 있군요... 한참 제가 부족하다는 것을 다시 깨달았습니다... 친절한 답변 감사드립니다 ㅠ
댓글 달기