
#include <iostream>
using namespace std;
void calculator(int calType, int a, int b)
{
if (calType == 1) // 덧셈
{
cout << a << " + " << b << " = " << a + b << "\n";
}
else if (calType == 2) // 뺄셈
{
cout << a << " - " << b << " = " << a - b << "\n";
}
else if (calType == 3) // 곱셈
{
cout << a << " * " << b << " = " << a * b << "\n";
}
else if (calType == 4) // 나눗셈
{
cout << a << " / " << b << " = " << a / b << "\n";
}
else // 그 이외의 숫자가 들어오면
{
cout << "잘못된 입력입니다." << "\n";
}
}
int main()
{
while (true)
{
cout << "사칙 연산 모드를 설정해주세요." << "\n";
cout << "1) 덧셈" << "\n";
cout << "2) 뺄셈" << "\n";
cout << "3) 곱셈" << "\n";
cout << "4) 나눗셈" << "\n";
cout << "-1) 나가기" << "\n";
int state = 0, inp1 = 0, inp2 = 0;
// 계산 뭐할지 입력
cout << "원하는 계산 입력해주세요 : ";
cin >> state;
if (state == -1)
{
break;
}
// 두 수 입력
cout << "첫 번째 수 입력 : ";
cin >> inp1;
cout << "두 번째 수 입력 : ";
cin >> inp2;
// 계산기 호출
calculator(state, inp1, inp2);
cout << endl;
}
return 0;
}
첫번째 코드
모든 분기를 만들었다. 코드더럽
괄호에 따른 연산 우선순위를 적용하려면 스택을 사용해야 하기때문에 구조를 모두 바꿔야한다.
istringstream ss(inp);
vector<string> tokens;
string token;
while (ss >> token)
{
tokens.push_back(token);
}
포인터 배열은 포인터를 원소로 갖는 배열
배열 포인터는 배열 전체를 가리키는 포인터
int x = 1, y = 2, z = 3;
int* ptrArr[3] = { &x, &y, &z };
int arr[3] = { 10, 20, 30 };
int (*ptr)[3] = &arr;
cout << *ptrArr[0] << endl;
cout << *ptrArr[1] << endl;
cout << *ptrArr[2] << endl;
cout << (*ptr)[0] << endl;
cout << (*ptr)[1] << endl;
cout << (*ptr)[2] << endl;
int arr[4] = {7, 3, 2, 5};
int* ptr = arr;
#include <iostream>
using namespace std;
int main()
{
int value = 25;
int* ptr = &value;
cout << "포인터를 통해 접근한 value의 값 : " << *ptr;
cout << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int score = 80;
int& score_ref = score;
cout << "레퍼런스를 통해 접근한 score의 값 : " << score;
cout << endl;
score_ref = 95;
cout << "레퍼런스를 통해 접근한 score의 값 : " << score;
cout << endl;
return 0;
}
C와 C++에서 char*은 문자열의 시작주소로 자주 쓰인다. cout은 char*를 만나면 자동으로 C-string(문자열)로 해석해서, 포인터가 가리키는 주소가 아니라 그 주소부터 시작하는 문자열을 출력한다.
즉, 그래서

64비트 cpu에서 레지스터가 64비트 이므로 한번에 64비트의 주소 처리가능 -> 그래서 포인터는 8바이트
int arr[3] = { 10, 20, 30 };
int (*ptr)[4] = &arr;
배열 포인터 타입이 배열 크기까지 타입에 포함되기 때문이다.
int arr[3] // 타입 int[3]
int(ptr)[4]; // 타입 int()[4];
&arr의 타입은 int(*)[3] 그러므로 이 코드는 서로 타입이 다르므로 실행 불가하다.