250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/CPP] 18.01. istream으로 입력받기 본문

C++/따배C++ 18강 입력과 출력

[C++/CPP] 18.01. istream으로 입력받기

polarcompass 2021. 12. 17. 00:40
728x90
#include<iostream>
#include<string>
#include<iomanip> // input / output manipulators

using namespace std;

int main()
{
    {cout << "Enter a number" << endl;

    int i;
    cin >> i;

    cout << i << endl;
    }

    {
        char buf[10]; // 마지막에 \0 캐릭터 붙임
        // 입력받는 글자수 제한
        cin >> std::setw(5) >> buf;
        cout << buf << endl; // 마지막 \0 때문에 4글자만 가져오는것처럼 보임
    }

    {
        char ch;

        while (cin >> ch)
            cout << ch;
    }

    {// 빈칸도 가져온다.
        char ch;
        while (cin.get(ch))
            cout << ch;
    }

    // 빈칸도 가져온다.
    {
        char buf[5];
        cin.get(buf, 5);
        cout << buf << endl;
    }

    {
        char buf[5];
        cin.get(buf, 5);
        // 몇 글자 읽었나 확인하는 함수 - gcount()
        cout << cin.gcount() << " " << buf << endl;
    }

    {
        char buf[100];
        // 줄바꿈 문자까지 다 읽어드리는 getline() 함수
        cin.getline(buf, 100);
        // 몇 글자 읽었나 확인하는 함수 - gcount()
        cout << cin.gcount() << " " << buf << endl;
    }

    {
        string buf;
        // string 사용시 getline() 사용법.
        getline(cin, buf);
                // 0이 나온다.
        cout << cin.gcount() << " " << buf << endl;
    }

    {
        char buf[1024];
        // 한 글자를 무시함.
        // cin.ignore();

        // 두 글자를 무시함
        cin.ignore(2);

        cin >> buf;
        cout << buf << endl;
    }

    {
        char buf[1024];
        // buffer의 첫글자를 들여다보기만하고 꺼내진 않는 함수 peek()
        cout << (char)cin.peek() << endl;

        cin >> buf;
        cout << buf << endl;
    }

    {
        char buf[1024];
        cin >> buf;
        cout << buf << endl;

        // buffer의 마지막 읽은 글자를 buffer로 다시 집어넣는 함수 - unget()
        cin.unget();

        cin >> buf;
        cout << buf << endl;
    }

    {
        char buf[1024];
        cin >> buf;
        cout << buf << endl;

        // 원하는 글자를 buffer에 다시 넣는 함수 - putback()
        cin.putback('A');

        cin >> buf;
        cout << buf << endl;
    }

    return 0;
}
728x90