buffer로 입력을 받는것.
글자수를 5글자로 제외했지만 초과된 글자는 그대로 buffer에 남아있어서 가져갈 수 있다.
한글자씩 받는 방법
#include <iostream>
#include <string>
#include <iomanip> //setw 글자수 제한
using namespace std;
int main()
{
char ch;
while (cin >> ch)
{
cout << ch;
}
return 0;
}
입력을 하면 한번에 천천히 받아온다. 그러나 띄어쓰기는 가져오지 않는다.
#include <iostream>
#include <string>
#include <iomanip> //setw 글자수 제한
using namespace std;
int main()
{
char ch;
while (cin.get(ch))
{
cout << ch;
}
return 0;
}
빈칸조차 입력을 받고 싶다면 cin.get(char)로 입력을 받으면 된다.
#include <iostream>
#include <string>
#include <iomanip> //setw 글자수 제한
using namespace std;
int main()
{
char buf[5];
while (cin.get(buf, 5))
{
cout << buf;
}
return 0;
}
버퍼로도 입력을 받을 수 있다.
#include <iostream>
#include <string>
#include <iomanip> //setw 글자수 제한
using namespace std;
int main()
{
char buf[5];
cin.get(buf, 5);
cout << cin.gcount() <<buf << endl;
//cin.gcount() 몇글자 읽어들였는지 확인을 해줌
return 0;
}
cin.gcount()를 사용하면 몇글자를 받았는지 확인 할 수 있다
get -> getline으로 하면 line단위로 읽어들인다
즉 한줄에서 buffer 이상으로 읽어들이면 그 이상은 안된다.
#include <iostream>
#include <string>
#include <iomanip> //setw 글자수 제한
using namespace std;
int main()
{
char buf[1024];
cin.ignore(2); //앞에 갯수만큼 무시를 함
cin >> buf;
cout << cin.gcount() << buf << endl;
return 0;
}
cin.ignore(n)은 앞 몇자리를 빼놓고 할지 결정하는 것. 파일 입출력때도 사용할 수 있다.
#include <iostream>
#include <string>
#include <iomanip> //setw 글자수 제한
using namespace std;
int main()
{
char buf[1024];
cout << (char)cin.peek() << endl;
cin >> buf;
cout << cin.gcount() << buf << endl;
return 0;
}
cin.peek()은 다음에 올 글자가 무엇인지 버퍼에서 살짝 꺼내는 것이다.
cin.unget() - 마지막에 읽은 것을 도로 넣은 것
cin.putback('버퍼에 넣을 내용') - 버퍼에 새로운 것을 넣는다