C++ STL - stringstream

less than 1 minute read

๊ตฌ๋ถ„์ž(delimiter)๋ฅผ ํ™œ์šฉํ•œ ๋ฌธ์ž์—ด ํŒŒ์‹ฑ(parsing)

  • ๊ตฌ๋ถ„์ž๋ฅผ ํ™œ์šฉํ•ด์„œ ๋ฌธ์ž์—ด์„ ํŒŒ์‹ฑํ•ด์•ผํ•  ๋•Œ ์œ ์šฉํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค.

ํ—ค๋”ํŒŒ์ผ sstream ์„ ์–ธ

#include <sstream>

stringstream ์‚ฌ์šฉ๋ฒ•

string str = "10,200,30,450";
stringstream ss(str);
string token;

while(getline(ss, token, ',')){ // ๊ตฌ๋ถ„์ž ์ฝค๋งˆ(,)
    // do something..
}

// ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์žˆ๋‹ค๋ฉด
string s = "190 205 39 40";
stringstream stm;
stm.str(s); // ์ŠคํŠธ๋ฆผ stm์˜ ๊ฐ’์„ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ์–ด ์ค€๋‹ค.

int num;
while(stm >> num){ // ์ž…๋ ฅ ์—ฐ์‚ฐ์ž ">>" ๋Š” ๊ณต๋ฐฑ ๋˜๋Š” ๊ฐœํ–‰๋ฌธ์ž๋ฅผ ๋ฒ„ํผ์— ๋‚จ๊ฒจ๋‘”๋‹ค.
    // do something..
}

Categories:

Updated:

Leave a comment