[C++] string to int

MinHee·2023년 3월 22일
0
post-thumbnail

stoi(string)

stringstream 클래스

string을 원하는 형식으로 변환 및 분할..?

#include <sstream>

  stringstream ssm;
  string str = "123 12abc 45ss 47as";
  ssm.str(str);
  int i;

while(ssm>>i){
	cout<<i<<endl;
}

출력

123
12
45
47

stringstream 객체를 연속하여 사용할 경우, clear() 함수를 호출하여야 함
<- 쓰레기값으로 파싱되어버림...

sstream.str("22 11");
sstream>>int_1>>int_2;

sstream.clear();

sstream.str("22 44");
sstream>>int_3>>int_4;

문자열 split 메소드

#include <vector>
#include <sstream>

vector<int> split (string str, char sep){
	vector<int> answer;
    stringstream sstream(str);
    string result;
    
    while(getline(sstream,result,sep){
    	answer.pushback(stoi(result));
    }
    
    return answer;    
}
#include <vector>
#include <sstream>

vector<int> split (string str, char sep){
	vector<int> answer;
    stringstream sstream(str);
    string result;
    
    while(getline(sstream,result,sep){
    	answer.pushback(
    }//쓰다 말았는데 생각 안남...
    
}
profile
성장하는 개발자

0개의 댓글