공부한거 정리하는 노트에요

[C++] 문자열 스트림(stringstream)

by 구설구설

문자열 스트림

문자열에 여러 가지 자료형이 들어왔을 때나 문자열을 파싱 할 때 용도에 맞게 파싱 하기 유용하다.

  • 헤더 ~#include <sstream>~ 

 

문자열 스트림

1. stringstream

  • 입출력 스트림: 입력 스트림, 출력 스트림을 모두 할 수 있다.

2. istringstream

  • 입력 스트림
  • 문자열을 공백과 ~'\n'~을 기준으로 여러개의 다른 형식으로 차례대로 분리할 때 편리하다.
  • 반복문 실행 시 자료형의 맞는 데이터가 없을 때까지 실행된다.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	istringstream iss("test\n123 aaa 456");
	string s1, s2;
	int i1, i2;
	iss >> s1 >> i1 >> s2 >> i2; // 문자열을 파싱하고 변수형에 맞게 변환한다.

	cout << s1 << endl; // test
	cout << i1 << endl; // 123
	cout << s2 << endl; // aaa
	cout << i2 << endl; // 456
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    string str1 = "1D2S#10S";
    string str2 = "1111DAWV2S#10S";

    istringstream iss1(str1);
    istringstream iss2(str2);
    int num1, num2;
    while (iss1 >> num1) cout << num1 << " ";
    cout << endl;
    while (iss2 >> num2) cout << num2 << " ";
    cout << endl;

    istringstream iss3(str1);
    istringstream iss4(str2);
    char ch1, ch2;
    while (iss3 >> ch1) cout << ch1 << " ";
    cout << endl;
    while (iss4 >> ch2) cout << ch2 << " ";
    cout << endl;
}

// 실행 결과
// 1 
// 1111 
// 1 D 2 S # 1 0 S 
// 1 1 1 1 D A W V 2 S # 1 0 S

3. ostringstream

  • 출력 스트림
  • 문자열 조립하거나 특정 형식을 문자열로 변환하기 위해 사용한다.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	ostringstream oss;
	string s1 = "abc", s2 = "gjw";
	int i1 = 19234;
	double d1 = 3.591;
	oss << s1 << "\n" << i1 << "\n" << s2 << "\n" << d1; // 문자열을 붙인다.
	cout << oss.str(); // 문자열을 꺼낸다.
}

// 실행 결과
// abc
// 19234
// gjw
// 3.591

4. getline()

  • 문자열을 공백이나 ~'\n'~이 아닌 다른 문자를 기준으로 분리하고 싶을 때 사용한다.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

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

// 실행 결과
// gkg
// qiew
// 789

 

문제 풀이

 

백준 9038번

일련의 문자열을 받은 뒤, 주어진 칸 수에 맞춰서 단어 단위로 줄 바꿈을 하고 줄 수를 출력하는 문제.

 

 

정답

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);

  int t;
  cin >> t;

  for (int i = 0; i < t; i++) {
    string a;
    int b;
    cin >> b;
    cin.ignore();
    getline(cin, a);
    stringstream ss(a);
    int temp = 0;
    int ans = 0;
    while (ss >> a) {
      temp += a.size();
      if (temp > b) {
        ans++;
        temp = a.size();
      }
      temp++;
    }
    cout << ans + 1 << '\n';
  }
}

'Language > C++' 카테고리의 다른 글

[C++] cout의 유효 숫자  (0) 2024.10.23

블로그의 정보

공부중임

구설구설

활동하기