Test/C

키보드로 세 단어 입력하여 사전 순서대로 출력

kiostory 2017. 8. 9. 16:53


1. 내가 한 것 : strcmp() 이용



#include <stdio.h>

int main(void)

{
    char word1[1000]={0}, word2[1000]={0}, word3[1000]={0};
    char input[1000];

    printf("세 단어 입력 : ");
    scanf("%s%s%s",word1, word2, word3);

    if(strcmp(word1,word2)<=0)
    {
       
       
        if(strcmp(word1,word3)<=0)
        {
           
            if(strcmp(word2,word3)<=0)
            {
                printf("%s %s %s",word1,word2,word3);
            }
            else printf("%s %s %s",word1,word3,word2);
           
        }
        else printf("%s %s %s",word3,word1,word2);
       
       
    }
    else printf("%s %s %s",word3,word2,word1);


    return 0;
}

-------------------------------------------------------

세 단어 입력 : student  mother  father
father mother student




2. 다른 방법 : strcpy() 및 임시변수 이용


#include <stdio.h>

#include <string.h>


int main(void)

{


     char str1[20], str2[20], str3[30];

     char temp[20];


     printf("세 개의 단어 입력 : ");

     scanf("%s%s%s", str1, str2, str3);


     // st1이 str2보다 사전의 뒤에 나오면 두 문자열을 바꾼다

     if(strcmp(str1, str2) > 0) 

     {

           strcpy(temp, str1);

          strcpy(str1, str2);

           strcpy(str2, temp);


     }


     // st1이 str3보다 사전의 뒤에 나오면 두 문자열을 바꾼다

     if(strcmp(str1, str3) > 0) 

     {

           strcpy(temp, str1);

           strcpy(str1, str3);

           strcpy(str3, temp);

     }


     // st2이 str3보다 사전의 뒤에 나오면 두 문자열을 바꾼다

     if(strcmp(str2, str3) > 0) 

     {

           strcpy(temp, str2);

           strcpy(str2, str3);

           strcpy(str3, temp);

     }


     printf("%s, %s, %s\n", str1, str2, str3);

     return 0;

}

-----------------------------------------------

세 개의 단어 입력 : student  mother  father
father, mother, student