반응형

1. 입출력


C언어에서는 pritnf, scanf로 입/출력을 했다면 이제 C++에서는 다르게 입/출력이 가능하다.


우선 헤더는 #include <iostream>을 추가해야하고 using namespace std를 이용한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
 
using namespace std;
 
int main()
{
    int a;
    double b;
    char c[200];
    cin >> a >> b >> c;
 
    cout << a << " "<<  b << " "<< c << endl;
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus



여기서 달라진 점은 scanf에서는 형식을 모두 정했어야 했는데 cin에서는 그냥 형식이 필요없다.

(컴파일러가 알아서 해석한다.)


cout에서도 마찬가지로 printf는 형식을 지정하지만 cout은 그렇지 않다.


endl의 의미는 endline으로 한줄 개행을 하겠다는 의미이다.(\n을 써도 된다.)



알아가기


cin으로 hello blog Crocus를 입력받아보자.  입력이 아마 받아지지 않을 것이다.


그 이유는 cin도 scanf와 마찬가지로 공백을 구분하기 때문이다.


따라서 C에서는 gets 혹은 get_s를 이용했다면 C++에서는 cin.getline라는 함수를 이용해보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdio>
#include <string>
 
using namespace std;
 
int main()
{
    char a[200];
    cin.getline(a, 200);
 
    cout << a;
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus






2. namespace 


namespace라는 것은 새로운 공간을 만들겠다는 것이다.


위의 코드에서는 using namespace std;라고 함으로써 std 공간을 쓴다는 것인데


같은 변수명 중복을 막기위해 namespace를 쓸 수 있다.


보통은 std 이름공간 내에서 모든 코드를 해결 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdio>
#include <string>
 
using namespace std;
 
namespace spaceA {
    int b = 2;
    char c[100= "hello world\n";
}
int main()
{
    int b = 3;
    char c[100= "bye world\n";
    printf("%d %d\n", spaceA::b, b);
    cout << spaceA::c << c << endl;
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus

 







반응형

'Tutoring > C++' 카테고리의 다른 글

다양한 입/출력 방식  (0) 2018.03.07
operator  (0) 2018.03.07
참조, template  (0) 2018.03.02
class 및 상속  (0) 2018.02.27