# [C++] cin.ignore()์œผ๋กœ ๋ฒ„ํผ ๋น„์šฐ๊ธฐ
Study Repository

[C++] cin.ignore()์œผ๋กœ ๋ฒ„ํผ ๋น„์šฐ๊ธฐ

by rlaehddnd0422

C++์—์„œ ์ŠคํŠธ๋ง์„ ์ž…๋ ฅ๋ฐ›์„ ๋•Œ std::cin์„ ์ด์šฉํ•ด ์ž…๋ ฅ๋ฐ›๊ณค ํ•ฉ๋‹ˆ๋‹ค.

์ด ๋•Œ ์ž…๋ ฅ๋ฐ›๋Š” ์ŠคํŠธ๋ง์— ๊ณต๋ฐฑ์„ ํฌํ•จํ•˜๊ณ  ์‹ถ์„ ๋•Œ, ์˜ˆ๋ฅผ ๋“ค๋ฉด "hello world" ๋ผ๋Š” ์ŠคํŠธ๋ง์„ ํ•˜๋‚˜์˜ ๋ณ€์ˆ˜์— ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” getline()์„ ํ†ตํ•ด ์ž…๋ ฅ์„ ๋ฐ›์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

ํ•˜์ง€๋งŒ ์ด ๋•Œ getline์„ ํ˜ธ์ถœํ•˜๊ธฐ ์ „ ๋ฐ›๋Š” ์ž…๋ ฅ์ด ์žˆ๋‹ค๋ฉด, ๋ฒ„ํผ์— ๊ฐœํ–‰๋ฌธ์ž(\n)๊ฐ€ ๋‚จ์•„์žˆ๊ธฐ ๋•Œ๋ฌธ์— '\n'์ด getline์— ๋ฐ”๋กœ ์ž…๋ ฅ๋˜์–ด ๋ฒ„๋ฆฌ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

 

cin์€ '\n'์„ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๊ณ  ์ž…๋ ฅ๋ฒ„ํผ์— ๋‚จ๊ฒจ๋‘  โžก๏ธ getline()์€ ์ž…๋ ฅ๋ฒ„ํผ์— ๋‚จ์•„์žˆ๋Š” '\n'์„ ๊ฐ€์ ธ์™€์„œ ์ฒ˜๋ฆฌ โžก๏ธ ์ž…๋ ฅ๋ฐ›์•„ ์ €์žฅ๋œ ์ŠคํŠธ๋ง ๋ณ€์ˆ˜์˜ ์•ž๋ถ€๋ถ„์— '\n'์ด ํ•จ๊ป˜ ์ €์žฅ๋จ. 

int n;
string s;

cin >> n;

getline(cin, s); // n์„ ์ž…๋ ฅ ์ดํ›„ ๋ฒ„ํผ์— '\n'์ด ๋‚จ์•„์žˆ์–ด '\n'์ด ๋ฐ”๋กœ ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด๊ฐ.

 

์ด ๋•Œ cin.ignore()์„ ํ†ตํ•ด ๋ฒ„ํผ๋ฅผ ๋น„์šธ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

int n;
string s;

cin >> n;

cin.ignore(); // n์„ ์ž…๋ ฅ์ดํ›„ ๋ฒ„ํผ์— ๋‚จ์€ '\n'์„ ๋ฒ„ํผ๋ฅผ ๋น„์›€์œผ๋กœ์จ ๋ฒ„ํผ์—์„œ ์‚ญ์ œ.
getline(cin, s);

 

๋ธ”๋กœ๊ทธ์˜ ์ •๋ณด

Study Repository

rlaehddnd0422

ํ™œ๋™ํ•˜๊ธฐ