C++ STL : <iostream>과 cin, cout

김종민·2025년 2월 26일

C++

목록 보기
1/5

1. <iostream>

C++ 표준 라이브러리 중 하나로 입출력을 위한 헤더파일이다.
(C의 stdio.h 와 비슷한 역할)

표준 라이브러리이므로 std namespace 내에 선언되어있다.


2. cin, cout

iostream 헤더 내에 정의된 객체의 종류는 cin, cout, cerr, clog 등이 있다.

cin : 표준 입력 스트림 (istream 클래스)
cout : 표준 출력 스트림 (ostream 클래스)

cerr: 표준 오류 출력 스트림
clog : 표준 로그 출력 스트림

* 위 4가지 객체 외에도 역할은 동일하나 wide char 데이터에 사용되는 객체가 있다.(wcin,wcout,wcerr,wclog)

스트림이란?

연속적인 데이터의 흐름 혹은 데이터를 전송하는 소프트웨어 모듈이다.

cin

>> 연산자를 사용해 입력받는다.

	std::cin >> 변수

cout

<< 연산자를 사용해 출력한다.

	std::cout << "출력할 내용"

>> , << 모두 입/출력 객체의 참조를 리턴하므로 이어서 사용할 수 있다.

int a, b;
std::cin >> a >> b;

std::cout << a << " & " << b;

입력

10 20

출력

10 & 20

3. 입출력 조작자(manipulator)

입출력 스트림을 조정할 수 있도록 도와주는 함수이다.
조작자 정리된 링크

자주 사용하는 조작자

  1. endl : 줄바꿈 & 출력 스트림 flush
int a, b;
std::cin >> a >> b;

std::cout << a << endl << b;

입력

10 20

출력

10
20
  1. setprecision(x) : 자릿수 설정 - <iomanip> 헤더에 있다.

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
  std::cout << std::fixed;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
  return 0;
}

출력

3.1416
3.14159
3.14159
3.141590000

정확하게 원하는 소수점 자릿수까지 표시하기 위해서는 fixed와 함께 써야한다.

* iomanip 헤더 없이 사용하려면 cout.precision(x) 로도 설정 가능하다.


참고 자료

https://www.tcpschool.com/cpp/cpp_intro_iostream
https://cplusplus.com/reference/iostream/
https://learn.microsoft.com/ko-kr/cpp/standard-library/iostream?view=msvc-170
https://unialgames.tistory.com/entry/CppProgramingOutputFormatting
https://www.geeksforgeeks.org/manipulators-in-c-with-examples/

profile
정리와 기록

0개의 댓글