C++ 배열입력받기

홍성우·2023년 5월 31일

C++

목록 보기
2/3

c++ 자료형
longlong -64bit(8byte) 정수형
char16_t - 16비트 문자(2Byte) // 유니코드 처리
char32_t - 32비트 문자(4Byte) // 유니코드 처리
auto - 컴파일러가 자동으로 형식을 규정하는 자료형
declty(expr) - expr와 동일한 자료형

c -> c++
malloc 함수, free함수 -> new(), delete()

#namespace

#include <iostream>

using namespace std;

int main()
{
	int* arr = new int[5];
	for (int i = 0; i < 5; ++i) {
		arr[i] = (i + 1) * 10;
	}

	for (int i = 0; i < 5; i++) {
		cout << arr[i] << endl;
	}
	// 동적할당 해제
	delete[] arr;


	

}

r-value 참조자

int main()
{
	// r-value - 이제 곧 사라질 대상에 대해 참조자를 부여 할수 있다는 것
	//int&& rdata = 3;

	int nInput = 0;
	cout << "Input Number:";
	cin >> nInput;
	
	int&& rdata = nInput + 5; // 임시 결과를 r-value 참조자 선언및 정의 (임시 결과 저장), 임시 결과는 연산에 활용된 후 소멸
	cout << rdata << endl;


	// r-value 참조
	int&& rData = TestFunc(10);

	rData += 10;
	cout << rData << endl;

}

1 이름과 나이를 입력받기

int main()
{
	int age = 0;
	cout << "나이를 입력하시오 :";
	cin >> age;
	cout << endl;

	char szName[32] = {0};
	cout << "이름을 입력하시오 :";
	cin >> szName;
	cout << endl;

	cout << "나의 이름" << szName << "," << age << "살 입니다." << endl;




}

2 배열 입력 받기 및 해제


int main()
{
	char *szBuffer = new char[12];

	cin >> szBuffer; // 버퍼가 자동으로 조정됨
	cout << endl;

	std::cout << szBuffer << std::endl;

	delete [] szBuffer;
}

3 배열 정렬

#include <iostream>
using namespace std;

void Swap(int& a, int& b) {
	int temp = a;
	a = b;
	b = temp;
}

void sort(int* aList) {
	// 버블 정렬
	for (int i = 0; i < 5; i++) {
		// int start = aList[i];
		for (int j = 0; j < 5; j++) {
			if (aList[i] < aList[j]) {
				int temp = aList[i];
				aList[i] = aList[j];
				aList[j] = temp;
			}
		}
	}
}


int main()
{
	int* aList = new int[5];
	for (int i = 0; i < 5; i++) {
		cin >> aList[i];
	}
	cout << endl;

	sort(aList);

	for (int i = 0; i <5; i++) {
		cout << aList[i] << ' ';
	}
	cout << endl;
}
profile
제 블로그를 방문해 주셔서 감사합니다

0개의 댓글