C++
ํ์ค ์
์ถ๋ ฅ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
#include <iostream>
iostream ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ c++ ํ์ค ์
์ถ๋ ฅ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ด๋ค. c์ธ์ด์ stdio.h
์ ํก์ฌํ๊ฒ ์ฌ์ฉ๋๋ค. c++์์๋ ํ์ ์ง์ ์(ex %d
, %f
)๋ฅผ ๋ฃ์ด์ฃผ์ง ์์๋ ๋ณ์๋ฅผ ํ์
์ ๋ง๊ฒ ์ ์ ํ ์
์ถ๋ ฅ์ ํด์ค๋ค. c++ ๊ธฐ๋ณธ ์
์ถ๋ ฅ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์๋ >>
์ <<
์ฐ์ฐ์๋ฅผ ์ ๊ณตํ๋ค. ์ด๋ ์
๋ ฅ์ ๋ฐ๋ >>
์ฐ์ฐ์๋ ๊ณต๋ฐฑ๋ฌธ์(space, Enter, Tab)์ ๊ธฐ์ค์ผ๋ก ์
๋ ฅ์ ๋ฐ๋๋ค.
#include <iostream>
#include <string>
int main(){
std::string input;
std::cin >> input;
std::cout << input << std::endl;
return 0;
}
cin
๊ณ ์์ค ์
๋ ฅ ๋ฐฉ์์ ์ฌ์ฉํ๋ฉด ์ฝ๋๊ฐ ๊ฐ๋จํด์ง์ง๋ง, ์ด์ ์ํ ์๋ ์ ํ ๋ํ ํด ์ ์๋ค. <cstdio>
์์ ๋๊ธฐํ๋ฅผ ๋๋ฉด ํจ์ฌ ๋นจ๋ผ์ง๋ค.
#include <iostream>
using namespace std;
int main(void){
cin.sync_with_stdio(false);
return 0;
}
namespace
namespace๋ ํน์ ์์ญ์ ์ด๋ฆ์ ์ค์ ํ ์ ์๋๋ก ํ๋ ๋ฌธ๋ฒ์ด๋ค. ์๋ก ๋ค๋ฅธ ๊ฐ๋ฐ์๊ฐ ๊ณต๋์ผ๋ก ํ๋ก์ ํธ๋ฅผ ์งํํ ๋ ๊ฐ์ ๊ฐ๋ฐํ ๋ชจ๋์ ํ๋๋ก ํฉ์น ์ ์๊ฒ ํด์ค๋ค.
[namespace]::[๋ณ์ ํน์ ํจ์]
namespace๋ผ๋ ์์ ๊ณต๊ฐ์ ๋ฐ๋ผ ๋ณ์๋ ํจ์๊ฐ ๊ฐ์ ์ด๋ฆ์์๋ ๋ค๋ฅด๊ฒ ๊ตฌ๋ถ์ด ๋ ์ ์๋ค.
#include <iostream>
namespace A{
void function(){
cout << "A namespace"<< endl;
}
}
namespace B{
void function(){
cout << "B namespace"<< endl;
}
}
int main(){
A::function();
B::function();
return 0;
}
์ฌ๊ธฐ์ ::
๋ ๋ฒ์์ง์ ์ฐ์ฐ์๋ก ์ด๋ค namespace์์ ์ด๋ค function์ ์ฌ์ฉํ ๊ฒ์ธ์ง ๋ช
์ํ ์ ์๋ค.
using namespace <namespace>
๊ธฐ๋ณธ์ ์ผ๋ก ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ using
ํค์๋๋ฅผ ์ด์ฉํด namespace๋ก ์ ์ธํด๋๊ณ ์์ ๋ช
์ํ์ง ์๊ณ ์ฌ์ฉํ ์ ์๋ค.
using namespace std;
int main(){
string input;
cin >> input;
cout << input << endl;
return 0;
}
string ๋ฌธ์์ด ์๋ฃํ
c++์ ํ์ค ๋ฌธ์์ด ์๋ฃํ์ ์ ๊ณตํ๋ค. ์ด๋ string ํค๋ ํ์ผ์ ์ ์๋์ด ์๋ค. ํด๋์ค๋ก ๊ตฌํ๋์ด์์ด ๊ฐ ์๋ฃํ๋ณ๋ก ๋ด์ฅํจ์๊ฐ ์์ผ๋ฉฐ, ์ด๋ฅผ ์ด์ฉํ ์ ์๋ค๋ ์ฅ์ ์ด ์๋ค.
char arr[SIZE]; // c์ธ์ด
string s; // cpp
์์์ ๋งํ >>
์ฐ์ฐ์๋ ๊ณต๋ฐฑ์ ๊ธฐ์ค์ผ๋ก ์
๋ ฅ๋ฐ๋๋ฐ, ํ ์ค ์ ์ฒด๋ฅผ ์
๋ ฅ๋ฐ๊ณ ์ถ์ ๊ฒฝ์ฐ์๋ getline()
ํจ์๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
int main(){
string input;
getline(cin, input);
cout << input << endl;
return 0;
}
๋ํ, c++์ string์ ๋ค๋ฅธ ์๋ฃํ์ผ๋ก์ ๋ณํ์ด ๊ฐํธํ๋ค. to_string()
, stoi()
์ ๊ฐ์ด ์ ์๋ฅผ ๋ฌธ์์ด๋ก, ๋ฌธ์์ด์ ์ ์๋ก ์ฝ๊ฒ ๋ณํํ ์ ์๋ค.
int i = 123;
string s = to_string(i);
cout << "์ ์ -> ๋ฌธ์์ด" << s << endl;
s = "456";
i = stoi(s);
cout << "๋ฌธ์์ด -> ์ ์" << i << endl;
๋์ ํ ๋น๋ c++์์ ๋ ๊ฐ๋จํ๊ฒ ํ ์ ์๋ค.
#include <iostream>
#define SIZE 100
using namespace std;
int *arr;
int main(){
arr = new int[SIZE]; // ๋์ ํ ๋น
for(int i=0; i < SIZE; i++){
cout << arr[i] << ' ';
}
delete arr; // ํ ๋น ํด์
return 0;
}
new
ํค์๋๋ก ๋์ ํ ๋น์ ํ ์ ์์ผ๋ฉฐ, ํ ๋น ํด์ ์์๋ delete
๋ก ํ ์ ์๋ค.
c์ธ์ด์ ๋น๊ต
c++๋ ๊ฐ์ฒด ์งํฅ ํจ๋ฌ๋ค์์ ๋ฐ๋ฅด๊ณ ์๋ ์ธ์ด, c์ธ์ด๋ ์ ์ฐจ์ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด
์ฆ, c++์ ๊ฐ์ฒด ์ค์ฌ์ ์ธ์ด์ด๊ณ , c์ธ์ด๋ ํจ์ ๊ธฐ๋ฐ์ ์ธ์ด์ด๋ค.
c++์ c์ธ์ด์ ๊ตฌ์กฐ์ฒด(struct)๋์ ์ class๋ฅผ ์ฌ์ฉํ๋ค.
c++์ ๊ณต์์ ์ผ๋ก ์์ธ์ฒ๋ฆฌ ๊ธฐ์ ์ ์ง์ํ๋ค.
Last updated
Was this helpful?