티스토리 뷰

노트

c++) cin.ignore()

tose33 2021. 12. 26. 15:15

https://www.cplusplus.com/reference/istream/istream/ignore/

 

istream::ignore - C++ Reference

public member function <istream> <iostream> istream& ignore (streamsize n = 1, int delim = EOF); Extract and discard characters Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares eq

www.cplusplus.com

https://www.cplusplus.com/reference/string/string/getline/

 

getline (string) - C++ Reference

function <string> std::getline (string) (1)istream& getline (istream& is, string& str, char delim); (2)istream& getline (istream& is, string& str); (1)istream& getline (istream& is, string& str, char delim); istream& getline (istream&& is, string& str, cha

www.cplusplus.com

 

우선 getline 함수는 레퍼런스를 보면 아래와 같다.

getline(cin, str) 이런식으로 코드가 있다면, 

cin 에서 delimiter(구분자)나 개행문자를 만날때까지 문자를 입력받아서 str 변수에 저장한다.

또한 

cin은 개행문자 ('\n')을 변수에 담지 않고, 입력 버퍼에 남겨둔다. 

=> getline()으로 입력 받았다면 '\n'을 변수에 담고 

      cin()으로 입력 받았다면 '\n'을 변수에 담지않는다. (입력버퍼에 남겨둔다)

 

따라서 아래와 같이 코드를 쓰면

abc를 cin 으로 입력 받고 나면, 개행문자가 버퍼에 남아있는 상태다.

따라서 바로 getline() 함수로 입력을 받으려 하면 버퍼에 있는 개행문자를 바로 만나기 때문에 입력받지 못하고 종료된다.

 

여기서 cin.ignore() 를 쓰면 해결된다.

 

ignore() 함수는 버퍼에서 n개의 문자 or 구분자 delim을 만날때까지 버퍼에서 문자를 읽어들여서 버린다.

따라서 아래와 같이 쓰면

abc를 입력 받은 후 버퍼에 남아있던 개행문자를 cin.ignore() 함수가 버려 버리므로써 

getline() 함수로 다음 문자들을 입력받을수 있다. 

 

 

 

##

cin 을 통해 숫자를 입력 받을 때는 바로 변수에 저장한다.

cin 을 통해 문자를 입력 받을 때는 입력 버퍼에 저장된 후, 버퍼에 저장 된 값을 읽어서 변수에 저장한다.

 

'노트' 카테고리의 다른 글

java) BufferedReader, BufferedWriter, StringBuilder  (0) 2021.12.30
c++) priority_queue cmp 구조체 정의  (0) 2021.12.27
언어별 2차원 배열 입력  (0) 2021.12.05
c++) bitset 클래스  (0) 2021.11.16
c++) transform 함수  (0) 2021.10.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
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
글 보관함