학부내용 예습/[ 2021 겨울 ] C++

[ C++] 1강 2강. 실습 코드

haena02 2022. 1. 3. 04:07
반응형

1. namepace 는 다르게 함수는 같게 홍길동 고길동 출력하기

#include<iostream>

namespace A_COM {

    void function(void) {
        std::cout << "홍길동" << std::endl;
    }
}

namespace B_COM {
    void function(void) {
        std::cout << "고길동";
    }
}

int main(void) {
    A_COM::function();
    B_COM::function();
}

 

 

2. 원하는 만큼 구구단 출력해주기

// 사용하여 구구단 출력하기 

#include <iomanip>
#include <iostream>

using namespace std;

void gugu(int a, int b) { // a단부터 b단까지 출력해주는 함수

    for (int i = 1; i < 10; i++) {
        for (int j = a; j <= b; j++) {
            cout << j << "*" << i << "=" << j * i << '\t';

        }
        cout << endl;
    }
}

int main(void) {

    int a;
    int b;

    cout << "구구단의 출려을 원하는 범위를 입력하세요" << endl;
    cin >> a >> b;

    if (a < b) {  // 올바르게 범위를 입력 했을때
        gugu( a, b);
    }
    else {  // 뒤에 입력한 숫자가 더 작을 때

        char C;
        cout << "첫 번째 입력 숫자가 더 크므로, 시작과 끝의 값을 바꿔서 출력할까요?(y/n)";
        cin >> C;
        if (C = 'y') { // 하겠다고 하면
            int c;  // a,b 자리 바꾸기
            c = a;
            a = b;
            b = c;
            gugu(a, b);
        }
        else { // 안하겠다고 하면
            cout << "종료합니다";
        }
    }

}

 

3. stringstream 사용하여 성적합 계산하기

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {

	string mystr;
	cout << "이름 (이름 국어 영어 수학) : ";
	getline(cin, mystr);
    
	stringstream ss;   // 객체생성
	ss.str(mystr);  
	int str; 
	int sum = 0;
	string name;
	ss >> name;  // 하나 읽어오기
	cout << name;
	while (ss >> str)  // 나머지 읽어와서 합하기
		sum +=str;
	cout << ":" << sum;

}
반응형