C++

C++에서 cout 총정리

김구티2 2024. 3. 9. 14:18

1. cout의 개념

C++에서 cout 객체는 class iostream의 객체이다. iostream 헤더 파일에 정의되어 있다. 이것은 표준 출력 장치로, 즉 모니터에 출력을 하는 데 사용된다. 이는 표준 C 출력 stream stdout과 연관되어 있다. 화면에 표시되기 위해 필요한 데이터는 삽입 연산자(<<)를 사용하여 표준 출력 스트림(cout)에 삽입된다.

 

예시1:

// C++ program to illustrate the use
// of cout object
#include <iostream>
using namespace std;

// Driver Code
int main()
{
     // Print standard output
     // on the screen
     cout << "Welcome to Gutiworld";

     return 0;
}

 

출력:

Welcome to Gutiworld

 

참고로, cout과 함께 삽입 연산자(<<)를 사용하면, 1개 보다 많은 변수가 프린트될 수 있다.

 

예시2:

// C++ program to illustrate printing
// of more than one statement in a
// single cout statement
#include <iostream>
using namespace std;

// Driver Code
int main()
{
     string name = "KimGuti";
     int age = 6;

     // Print multiple variable on
     // screen using cout
     cout << "Name : " << name << endl
     << "Age : " << age << endl;

     return 0;
}

 

출력:

Name : KimGuti

Age : 6

 

추가로, cout문은 일부 멤버 함수와 함께 사용할 수도 있다.

cout.write(char *str, int N)는 str에서 읽은 첫 번째 N자를 프린트한다.

cout.put(char &ch)은 문자 ch에 저장된 문자를 프린트한다.

cout.precision(int N)은 Float 값을 사용할 경우, 소수점을 고정시켜서 정수 부분과 소수점 부분을 더해 총 N자리를 표기하겠다는 것이다. 즉, 5.20244일 때는 6일 것이고, 688.245일 때도 6인 것이다.

 

예시3:

// C++ program to illustrate the use
// of cout.write() and cout.put()
#include <iostream>
using namespace std;

// Driver Code
int main()
{
     char gfg[] = "Welcome at GT";
     char ch = 'e';

     // Print first 6 characters
     cout.write(gfg, 6);

     // Print the character ch
     cout.put(ch);
     return 0;
}

 

출력:

Welcome

 

예시4:

// C++ program toillustrate the use
// of cout.precision()
#include <iostream>
using namespace std;

// Driver Code
int main()
{
     double pi = 3.14159783;

     // Set precision to 5
     cout.precision(5);

     // Print pi
     cout << pi << endl;

     // Set precision to 7
    cout.precision(7);

    // Print pi
    cout << pi << endl;

    return 0;
}

 

출력:

3.1416

3.141598

 

728x90

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

C++ 조정자(Manipulator) 총정리  (0) 2024.03.10
C++ cerr 총정리  (0) 2024.03.10
C++에서 cin 총정리  (0) 2024.03.09
C++ 연산자(Operator) 총정리  (0) 2024.03.09
C++ if else문 총정리  (0) 2024.03.08