Machineboy空

C++ 기초 문법 다지기 예제 모음4 - 함수 본문

Computer/Coding Test

C++ 기초 문법 다지기 예제 모음4 - 함수

안녕도라 2024. 10. 24. 22:36

프로그램의 일부 로직을 함수를 사용하여 별도로 추상화하면 코드가 더 읽기 쉬워지고 유지보수도 용이하다.

 

함수는 복잡한 연산을 추상화시켜 줄 뿐만 아니라 재사용을 가능케 하는 요소이기도 하다.

 

카드 대금을 상환하는 데는 생각보다 더 오랜 시간이 걸린다. 그리고 상환하는 공식 또한 매우 복잡하다. 이러한 공식의 복잡도를 함수로 숨기는 것 역시 여러분의 코드가 조직화되도록 하는 데 도움이 된다.

 

대규모 함수는 사용하기도 어렵고 관리하는 것도 쉽지 않다. 그래서 로직을 나누어 여러 개의 작은 함수로 구성하는 것이 훨씬 좋다. 프로그램은 이렇게 만들어진 함수들을 차례로 호출하기만 하면 된다.


예제 24. 에너그램 점검

두 개의 문자열을 비교하여 서로가 애너그램(anagram)인지를 검사하는 프로그램을 작성하라.

*애너그램: 단어 문장을 구성하고 있는 문자의 순서를 바꾸어 다른 단어나 문장을 만드는 것

출력)
Enter two strings and I'll tell you if they are anagrams:
Enter the first string : note
Enter the second string: tone
"note" and "tone" are anagrams.
#include <iostream>
#include <string>
#include <vector> // vector를 사용하기 위해 추가
#include <algorithm> // sort를 사용하기 위해 추가

using namespace std;

bool isAnagram(string a, string b) {
    // 문자열의 길이가 다르면 애너그램이 아님
    if (a.length() != b.length()) return false;

    // 벡터를 초기화
    vector<char> str(a.begin(), a.end());
    vector<char> str2(b.begin(), b.end());

    // 두 문자열을 정렬
    sort(str.begin(), str.end());
    sort(str2.begin(), str2.end());

    // 정렬된 두 문자열이 같으면 애너그램
    return str == str2;
}

int main() {
    string first, second;

    cout << "Enter two strings and I'll tell you if they are anagrams:\n";

    cout << "Enter the first string: ";
    cin >> first;

    cout << "Enter the second string: ";
    cin >> second;

    if (isAnagram(first, second)) {
        cout << "\"" + first + "\"" + " and " + "\"" + second + "\"" + " are Anagrams." << endl;
    } else {
        cout << "\"" + first + "\"" + " and " + "\"" + second + "\"" + " are not Anagrams." << endl;
    }

    return 0;
}

 

문자열 다루는 아이디어.. 배워두기!

애너그램, 펠린드롬 등은 고전이니까 아이디어를 외워둬야 해.


 

예제 25. 암호 길이 점검

암호의 복잡도를 결정하는 프로그램을 작성하라.

✴아주 약한 암호는 숫자로만 구성되고 길이도 8글자 미만임
✴약한 암호는 영문자로만 구성되고 길이도 8글자 미만임
✴강한 암호는 영문자와 한 개이상의 숫자로 구성되어 있으며 길이는 8글자 이상임
✴아주 강한 암호는 영문자, 숫자, 특수문자로 구성되어 있으며 길이는 8글자 이상임

출력)
The password '12345' is a very weak password.
The password 'abcdef' is a weak password.
The password 'abc123xyz' is a strong weak password.
The password '1337h@xor!' is a very strong password.
#include <iostream>
#include <string>
using namespace std;

string password;

// 영문, 숫자, 특수문자 구분 어떻게? 
string checkPassword(string password){
    int alphabet = 0, num = 0, special = 0;

    for(char c : password){
        if(c >= 'a' && c <= 'z'){
            alphabet++;
        }else if(c >= 'A' && c <= 'Z'){
            alphabet++;
        }else if(c >= '0' && c <= '9'){
            num++;
        }else{
            special++;
        }
    }

    if(password.length() < 8){
        if(alphabet == 0 && special == 0) return "very weak password.";
        if(num == 0 && special == 0) return "weak password.";
    }else{
        if(alphabet > 0 && num > 0 && special > 0) return "very strong password";
        if(alphabet > 0 && num > 0) return "strong weak password";
        return "";
    }

}

int main() {

    cout << "Input Password";
    cin >> password;

    cout << "The password '" + password + "' is a " + checkPassword(password);  
    
    return 0;
}

https://maincodes.tistory.com/68

 

[C/C++] ASCII 코드값을 이용하여 문자열 내 알파벳, 대소문자, 공백, 숫자 식별(분류)하기 + 대소문

[C/C++] ASCII 값을 이용하여 문자열 내 알파벳, 대소문자, 공백, 숫자 식별(분류)하기 + 대소문자 변환하기 안녕하세요 JollyTree입니다 (•̀ᴗ•́)و C/C++에서 char 자료형의 문자 변수는 0에서 127 사이

maincodes.tistory.com


예제 26. 카드 대금 상환 기간

출력)
What is your balance? 5000
What is the APR on the card (as a percent)? 12
What is the monthly payment you can make? 100
It will take you 70 months to pay off this card.

예제 27. 입력값 검증

이름과 성, 사번, 우편번호를 입력받은 다음 다음과 같은 규칙에 맞는지를 점검하는 프로그램을 작성하라.

✴이름은 반드시 넣어야 한다.
✴성은 반드시 넣어야 한다.
✴이름과 성은 최소한 두 글자 이상이어야 한다.
✴사번은 AA-1234의 형태가 되어야 한다. 즉, 두 글자의 알파벳, 하이픈, 4자리 숫자로 구성되어야 한다.
✴우편번호는 반드시 숫자여야 한다.

출력)
Enter the first name: J
Enter the last name: 
Enter the ZIP code: ABCDE
Enter an employee ID: A12-1234
"J" is not a valid first name. It is too short.
The last name must be filled in.
The ZIP code must be numeric.
A12-1234 is not a valid ID
There were no errors found.

https://life-with-coding.tistory.com/411

 

[C++][STL] Vector 기본 사용법 및 예제 활용

인트로 안녕하세요! 오늘은 C++ STL중 하나인 벡터(Vector)의 기본 함수와 예제에 대해서 알아보도록 하겠습니다. 벡터 기본함수는 push_back, pop_back, front, back, clear, begin, end, rbegin, rend, reverse 등이 있

life-with-coding.tistory.com

 


정리

  • 에너그램, 팰린드롬 등의 고전 아이디어는 숙지해두자!
  • 숫자, 영문자, 특수문자를 감별하기 위한 아스키코드 활용법 알아두자!