반응형

std::cin

  • 입력값 확인 및 재입력 처리
#include <iostream>

int main()
{
    int n = 0;

    while(1)
    {
        std::cin >> n; //숫자 입력을 기대하였으나 사용자가 문자를 입력 하였을때

        if (std::cin.fail()) // 정상적인 입력 여부 확인
        {
            std::cout << "실패" << std::endl;
            std::cin.clear(); // cin의 상태를 나타내는 비트 초기화
            std::cin.ignore(256, '\n'); // 내부적으로 사용되는 입력 버퍼 제거, \n만날때까지 최대 256자 제거
            continue;
        }
        break;
    }

    std::cout << n << std::endl;
}

std::cin

  • 1개의 단어 입력 처리
#include <iostream>
#include <string>

int main()
{
    std::string w;
    std::cin >> w; // 1개의 단어 입력
        
    std::cout << w << std::endl;
}
  • 문장(다중 단어) 입력 처리
#include <iostream>
#include <string>

int main()
{  
    std::string s;
    std::getline(std::cin, s); // 문장 전체 입력

    std::cout << s << std::endl;
}
반응형

반응형

cout의 원리

  • cout은 ostream 타입의 객체
  • <<연산자를 각각의 primitive 타입에 대해서 연산자 오버로딩 한 것
    • cout << 5 : cout.operator<<( int )
    • cout << 3.4 : cout.operator<<( double )

ostream 구현

  • 모든 primitive 타입에 대해서 operator<<() 연산자 함수 제공
  • 연속 출력을 위해서 리턴 값을 자기 자신을 참조 리턴
  • 실제 화면 출력 원리
    • 각 OS가 제공하는 시스템 콜 사용
      • Windows : windows API - WriteFile()
      • Linux : Linux system call - write()
#include <cstdio>
using namespace std;

// std::cout 원리 파악을 위한 구현 예제
namespace std
{
    class ostream
    {
    public:
        ostream& operator<<(int n)
        {
            printf("%d", n);
            return *this;
        }
        ostream& operator<<(double d)
        {
            printf("%f", d);
            return *this;
        }
    };
    ostream cout;
}

int main()
{
    cout << 3; // ostream& operator<<(int n) 호출됨
    cout << 3.4; // ostream& operator<<(double d) 호출됨
    cout << 3 << 4; // 자기 자신을 참조로 리턴하므로 연속 출력 가능
}

유니 코드 출력 팁

  • cout의 정확한 타입은 ostream이 아닌 basic_ostream 템플릿
    • typedef basic_ostream<char> ostream;
    • typedef basic_ostream<wchar_t> wostream;
  • 유니코드 출력
    • ostream cout;
    • wostream wcout;

endl 원리

  • endl은 함수
    • cout << endl;
    • endl(cout);
  • hex, dec, alpha... 등은 모두 함수
    • 입출력 조정자 함수(i/o manipulator)
  • 사용자가 직접 만들 수 있음
    • tab 예제
#include <cstdio>
using namespace std;

namespace std
{
    class ostream
    {
    public:
        ostream& operator<<(int n)
        {
            printf("%d", n);
            return *this;
        }
        ostream& operator<<(double d)
        {
            printf("%f", d);
            return *this;
        }
        ostream& operator<<(char c) // os << '\n'; 지원 위한 연산자
        {
            printf("%c", c);
            return *this;
        }
        ostream& operator<<(ostream& (*f)(ostream&)) // endl 함수 포인터를 담기 위한 연산자
        {
            f(*this); // endl 함수에 자신의 객체 참조 전달
            return *this;
        }
    };
    ostream cout;

    ostream& endl(ostream& os) // 개행
    {
        os << '\n';
        return os;
    }
    
    ostream& tab(ostream& os) // 탭 예제
    {
        os << '\t';
        return os;
    }    
    
}

int main()
{
    cout << 3 << endl; // cout.operator<<( 함수 포인터 )
    cout << 3 << tab << endl; // cout.operator<<( 함수 포인터 )
}

cout 사용자 정의 객체 출력

  • operator<<() 연산자를 일반 함수로 제공하면 가능
class Complex
{
    int re, im;
public:
    Complex(int r = 0, int i = 0) : re(r), im(i) {}

    friend std::ostream& operator<<(std::ostream&, const Complex&);
};

// ostream의 연산자는 상수 함수가 아니므로 접근을 위해 const 객체를 사용하지 않음
std::ostream& operator<<(std::ostream& os, const Complex& c)
{
    os << c.re << "," << c.im; // 사용자 정의 객체의 멤버 데이터를 개별 출력
    return os;
}

int main()
{
    Complex c(1, 1);

    std::cout << c; // cout으로 사용자 정의 객체 출력
}

 

 

반응형

'프로그래밍 언어 > C++' 카테고리의 다른 글

C++ 증감 연산자(++, --)  (0) 2019.05.10
C++ 함수 객체(Function Object)  (0) 2019.05.10
C++ 연산자 재정의 - 기본 개념  (0) 2019.05.08
C++ static, const, this  (0) 2019.05.07
C++ 복사 생성자  (0) 2019.05.06

+ Recent posts