입출력 관련 함수들 (setw, setprecision, get, getline, ignore, putback, unget, peek)
· 배운 것 · 2분 읽기
setw, setprecision
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a = 1.222222f;
char buf[5];
//5개까지 입력을 받음, 마지막은 nullchar용
cin >> setw(5) >> buf;
cout << buf << endl;
//fixed쓰면 소숫점, 여기서는 소숫점 두글자까지 출력됨
cout <<fixed << setprecision(2)<< a << endl;
return 0;
}
get, getline (char), getline ( string )
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char buf[100];
cin.get(buf, 100);
cout <<cin.gcount() << buf << endl;
//getline은 줄바꿈 ch도 읽어옴 그래서 1이 나옴
cin.getline(buf, 100);
cout << cin.gcount() << buf << endl;
//string일때 getline
string str;
getline(cin, str);
cout << str << endl;
return 0;
}
ignore, putback, unget, peek
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char buf[100];
//버퍼에 무슨글자가 있는지 살짝들여다본다
//버퍼에서 불러들어오는건 아님, 앞글자만 나옴
cout << (char)cin.peek() << endl;
//두글자 무시
cin.ignore(2);
cin >> buf;
cout << buf << endl;
//버퍼에 글자를 넣는다.
cin.putback('a');
//다시 buffer에 마지막글자를 넣는다.
cin.unget();
cin >> buf;
cout << buf << endl;
return 0;
}