텍스트 파일에서 첫번째 짧은 단어와 두번째 짧은단어, 그리고 첫번째 긴 단어와 두번째 긴 단어를 출력하는 예제...

quarterhorse의 이미지

안녕하세요, 다름이 아니라, 예제를 연습하다가 질문 드립니다.

텍스트 파일에서 첫번째 짧은 단어와 두번째 짧은단어, 그리고 첫번째 긴 단어와 두번째 긴 단어를 출력하는 예제가 있는데요,

첫번째 짧은 단어와 두번째 짧은 단어를 출력해주는것은 성공했는데,

첫번째 긴 단어와 두번째 긴 단어를 출력하는것을 실패했습니다.

실제로 콘솔에서 실행해보면 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;
}

생각대로라면 짧은거 판별해주는 로직은 잘못되있는거 같진 않은데, 긴거 판별해 주는 로직이 감이 안잡힙니다...

어떻게 수정해야 첫번째 긴 단어와 두번째 긴 단어를 출력할 수 있을까요.... ㅠㅠ

도움 주시면 정말 감사드리겠습니다....

HDNua의 이미지

#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;
        */
}

두 문장의 길이가 같은 경우 등의 예외 처리는 안 되어있습니다.

저는 이렇게 생각했습니다.

quarterhorse의 이미지

더욱 깔끔하게 이런식으로도 나올수 있군요... 한참 제가 부족하다는 것을 다시 깨달았습니다... 친절한 답변 감사드립니다 ㅠ

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.