Skip to content

문자열 파싱 함수  #6

@gyurim

Description

@gyurim

문자열 파싱 함수

1. istringstream

  • string을 입력받아 다른 형식으로 바꿔주는 기능.
  • istringstream은 공백을 기준으로 문자열을 파싱하여 변수의 형식에 맞게 변환해준다.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	istringstream iss("test 123 aaa 456");
	string s1, s2;
	int i1, i2;
	iss >> s1 >> i1 >> s2 >> i2; // 공백을 기준으로 문자열을 parsing하고 변수 형식에 맞게 변환
	cout << s1 << endl;
	cout << s2 << endl;
	cout << i1 << endl;
	cout << i2 << endl;
}

2. ostringstream

  • ostringstream은 string을 조립하거나, 특정 수치를 문자열로 변환하기 위해 사용한다.
  • ostringstream은 문자열을 붙이는 것 외에도 int나 double형과 같은 수치값을 간단하게 string으로 바꿀 수 있다.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	ostringstream oss;
	string s1 = "abc", s2 = "gjw";
	int i1 = 198;
	double d1 = 3.591;
	// 문자열 붙이기 
	oss << s1 << "\n" << i1 << "\n" << s2 << "\n" << d1;
	// str() : ostringstream 객체에서 조립된 문자열을 꺼낸다. 
	cout << oss.str() << endl; // str() : ostringstream 객체에서 조립된 문자열을 꺼낸다. 
}

3. string stream

  • stringstream은 가지고 있는 string에서 공백과 \n을 제외한 문자열을 차례대로 뻬내는 역할을 수행
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	string str = "123 456 \nabc\ndef", token;
	stringstream ss(str);
	while (ss >> token) {
		cout << token << endl;
	}
}
  • 만약 공백이나 \n이 아닌 다른 문자를 기준으로 문자열을 분리하고 싶다면?
    • getline() 함수 사용
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	string str = "gkg|giew|789", token;
	stringstream ss(str);
	while(getline(ss, token, '|') {
		cout << token << endl;
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions