Legacy
[C++] 키보드 입출력 cin / cin.get / cin.getline / getline 이해와 사용법, 차이점
Marco
2020. 7. 15. 01:21
728x90
1. cin - istream 클래스의 인스턴스 / '>>' 연산자와 주로 동작함
How to use :
example :
#include <iostream> // std::cin, std::cout
int main () {
char c;
std::cout << "Enter the name of an existing text file: ";
std::cin >> c; // get char
std::ifstream is(str); // open file
char c;
while (is.get(c)) // loop getting single characters
std::cout << c;
is.close(); // close file
return 0;
}
example :
feature :
-> 입력버퍼에서 공백, \n 무시 제외한 값을 저장
* \n 버퍼가 남음
2. cin.get()
How to use :
#include <iostream>
// (1) single character
int get();
istream& get (char& c);
// (2) c-string
istream& get (char* s, streamsize n);
istream& get (char* s, streamsize n, char delim);
// (3) stream buffer
istream& get (streambuf& sb);
istream& get (streambuf& sb, char delim);
example :
// istream::get example
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
int main () {
char str[256];
std::cout << "Enter the name of an existing text file: ";
std::cin.get (str,256); // get c-string
std::ifstream is(str); // open file
char c;
while (is.get(c)) // loop getting single characters
std::cout << c;
is.close(); // close file
return 0;
}
feature :
-> 입력버퍼에서 하나의 문자만 저장 공백, \n 포함함
3. cin.getline()
How to use :
#include <iostream>
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
example :
// istream::getline example
#include <iostream> // std::cin, std::cout
int main () {
char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);
std::cout << name << "'s favourite movie is " << title;
return 0;
}
feature :
-> 공백, \n 입력 받음 문자열 문자 받음
-> 마지막 문자 NULL
-> getline() 과 다른함수임
4. getline()
How to use :
#include <string>
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
example :
// extract to string
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
C++ Reference
cin : www.cplusplus.com/reference/iostream/cin/?kw=cin
cin.get() : www.cplusplus.com/reference/istream/istream/get/?kw=cin.get
cin.getline() : www.cplusplus.com/reference/istream/istream/getline/
getline() : www.cplusplus.com/reference/string/string/getline/
고마운분 : https://modoocode.com/213
728x90