Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-16 04:51
관리 메뉴

nomad-programmer

[Programming/C] 문자열 추가, 삭제, 출력, 정렬 간단한 예제 본문

Programming/C

[Programming/C] 문자열 추가, 삭제, 출력, 정렬 간단한 예제

scii 2021. 1. 21. 23:27
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void Menu(){
    puts("");
    puts("1. 문자열 입력");
    puts("2. 문자열 삭제");
    puts("3. 문자열 출력");
    puts("4. 문자열 정렬");
    puts("5. 종료");
}

void ClearBuffer(){
    while(getchar() != '\n');
}

char* Input(){
    char temp[100];
    char* str;
    printf("100자 이하의 문자 입력: ");
    scanf("%s", temp);
    ClearBuffer();
    str = (char*)malloc(sizeof(char)*strlen(temp)+1);
    strcpy(str, temp);
    return str;
}

void Remove(char* strArray[], int* sCount){
    char temp[100];
    if(*sCount == 0){
        return;
    }
    printf("삭제할 문자열을 입력하시오: ");
    scanf("%s", temp);
    ClearBuffer();
    for(int i=0; i<*sCount; i++){
        if(strcmp(strArray[i], temp) == 0){
            free(strArray[i]);
            --*sCount;
            while(i < *sCount){
                strArray[i] = strArray[i+1];
                i++;
            }
            break;
        }
    }
}

void Output(char* strArray[], int sCount){
    puts("");
    for(int i=0; i<sCount; i++){
        printf("%d : %s\n", i, strArray[i]);
    }
}

void Swap(char** a, char** b){
    char* temp = *a;
    *a = *b;
    *b = temp;
}

void Sort(char* strArray[], int sCount){
    int min;
    for(int i=0; i<sCount-1; i++){
        min = i;
        for(int j=i+1; j<sCount; j++){
            if(strcmp(strArray[j], strArray[min]) < 0){
                min = j;
            }
        }
        Swap(&strArray[i], &strArray[min]);
    }
}

int main(int argc, const char * argv[]) {
    char ch;
    char* strArray[100];
    int sCount = 0;
    int bContinue = 1;
    
    while(bContinue){
        Menu();
        scanf("%c", &ch);
        ClearBuffer();
        switch(ch){
            case '1':
                if(sCount < 100){
                    strArray[sCount++] = Input();
                }
                break;
            case '2':
                Remove(strArray, &sCount);
                break;
            case '3':
                Output(strArray, sCount);
                break;
            case '4':
                Sort(strArray, sCount);
                break;
            case '5':
                bContinue = !bContinue;
                break;
            default:
                puts("1~5까지 입력 가능!!");
        }
    }
    
    for(int i=0; i<sCount; i++){
        free(strArray[i]);
    }

    return 0;
}

눈여겨 봐야할 부분은 ClearBuffer() 함수이다. scanf 함수는 기본적으로 입력을 받아 엔터(\n) 전의 데이터만을 취한다. 그렇기 때문에 입력 버퍼에는 아직도 '\n' 이 남아 있는 상태이다. 이 상태에서 다른 출력을 하거나 입력을 하려고한다면 \n이 자동으로 들어가서 원치 않는 결과를 얻을 것이다. 따라서 Buffer를 항상 유념해야 한다.

간단한 예제라서 따로 설명할 것이 없다.


다음은 소문자, 대분자 문자열을 랜덤으로 발생시키는 예제이다.

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

typedef struct _sData{
    char* smallStr;
    char* largeStr;
} DATA, *PDATA;

char AlphaRandSmall(){
    return rand() % 26 + 'a';
}

char AlphaRandLarge() {
    return rand() % 26 + 'A';
}

char* StrRand(int type, int n){
    char temp[20] = {0};
    char* str;
    if(type == 1){
        for(int i=0; i<n; i++){
            temp[i] = AlphaRandSmall();
        }
    }
    else if (type == 2){
        for(int i=0; i<n; i++){
            temp[i] = AlphaRandLarge();
        }
    }
    else{
        return NULL;
    }
    str = (char*)malloc(strlen(temp)+1);
    strcpy(str, temp);
    return str;
}

int main(int argc, const char * argv[]) {
    DATA darr[10];
    
    for(int i=0; i<10; i++){
        darr[i].smallStr = StrRand(1, rand() % 5 + 6);
        darr[i].largeStr = StrRand(2, rand() % 5 + 6);
    }
    for(int i=0; i<10; i++){
        printf("%-20s %-20s\n", darr[i].smallStr, darr[i].largeStr);
    }
    puts("===================================================");
    for(int i=0; i<10; i++){
        printf("%-20s %-20s\n", (darr+i)->smallStr, (darr+i)->largeStr);
    }
    
    for(int i=0; i<10; i++){
        free(darr[i].smallStr);
        free(darr[i].largeStr);
    }

    return 0;
}

/* 결과
rfkqyuqf             KXYQVNRTYS          
rzrmzlygf            EULQFPDB            
lqdqrrc              WDNXEUO             
qeklai               GDPHCSPIJT          
bsfyfvlad            PBFUDKK             
rwqaozmix            PIFEFFEC            
hbvfukbyeq           QOJWTWOS            
leeztxwj             KNGBQQM             
xqcqptkhhq           QDWFCA              
ssyoqcjomw           FBDFXU              
===================================================
rfkqyuqf             KXYQVNRTYS          
rzrmzlygf            EULQFPDB            
lqdqrrc              WDNXEUO             
qeklai               GDPHCSPIJT          
bsfyfvlad            PBFUDKK             
rwqaozmix            PIFEFFEC            
hbvfukbyeq           QOJWTWOS            
leeztxwj             KNGBQQM             
xqcqptkhhq           QDWFCA              
ssyoqcjomw           FBDFXU    
*/

이것도 마찬가지로 문자열을 저장할 힙 영역에 메모리에 문자열을 저장하고 있다. 발생시킨 문자열의 크기만큼만 동적할당하기에 타이트한 메모리를 얻을 수 있다.


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

typedef struct _person{
    char* name;
    char* phone;
    int age;
} PERSON, *PPERSON;

void ClearBuffer(){
    while(getchar() != '\n');
}

void Menu(){
    puts("");
    puts("1. insert tel");
    puts("2. delete tel");
    puts("3. print tel");
    puts("4. sort tel");
    puts("5. exit");
    puts("=====================");
}

char* InputStr(){
    char temp[100];
    char* str;
    
    fgets(temp, sizeof(temp), stdin);
    str = (char*)malloc(sizeof(char) * strlen(temp) + 1);
    // '\n' fgets 함수는 \n문자도 입력으로 들어온다. 따라서 아래와 같이 적절히 변환을 해야 한다.
    temp[strlen(temp)-1] = '\0';
    strcpy(str, temp);
    return str;
}

PPERSON InputPerson() {
    PPERSON p = (PPERSON)malloc(sizeof(PERSON));
    ClearBuffer();
    fputs("insert name: ", stdout);
    p->name = InputStr();
    fputs("insert tel: ", stdout);
    p->phone = InputStr();
    fputs("insert age: ", stdout);
    scanf("%d", &p->age);
    return p;
}

void Freememory(PPERSON p){
    free(p->name);
    free(p->phone);
    free(p);
}

void Remove(PPERSON strArray[], int* sCount){
    char name[100];
    if(*sCount == 0){
        return;
    }
    ClearBuffer();
    fputs("insert name: ", stdout);
    fgets(name, sizeof(name), stdin);
    name[strlen(name)-1] = '\0';
    for(int i=0; i<*sCount; i++){
        if(strcmp(strArray[i]->name, name) == 0){
            Freememory(strArray[i]);
            --*sCount;
            while(i < *sCount){
                strArray[i] = strArray[i+1];
                i++;
            }
            break;
        }
    }
}

void Output(PPERSON perArray[], int sCount){
    for(int i=0; i<sCount; i++){
        printf("[%d]: %s, %s, %d\n", i, perArray[i]->name, perArray[i]->phone, perArray[i]->age);
    }
}

void Swap(PPERSON* a, PPERSON* b){
    PPERSON temp = *a;
    *a = *b;
    *b = temp;
}

void Sort(PPERSON perArray[], int sCount){
    int i, j, min;
    for(i=0; i<sCount-1; i++){
        for(min=i, j=i+1; j<sCount; j++){
            if(strcmp(perArray[j]->name, perArray[min]->name) < 0){
                min = j;
            }
        }
        Swap(&perArray[i], &perArray[min]);
    }
}

int main(int argc, const char * argv[]) {
    PPERSON personArray[100];
    int sCount = 0, bContinue = 1;
    while(bContinue){
        Menu();
        switch(getchar()){
            case '1':
                if(sCount < 100){
                    personArray[sCount++] = InputPerson();
                }
                break;
            case '2':
                Remove(personArray, &sCount);
                break;
            case '3':
                Output(personArray, sCount);
                break;
            case '4':
                Sort(personArray, sCount);
                break;
            case 53:
                bContinue = !bContinue;
                break;
            default:
                puts("1~5 input!!");
        }
        ClearBuffer();
    }
    
    for(int i=0; i<sCount; i++){
        Freememory(personArray[i]);
    }

    return 0;
}
Comments