C++{Diary}
[C++] sstream 헤더파일(개념, 개념잡기코드, 연습문제 코드)
토끼여우
2023. 7. 16. 20:10
728x90
SMALL
sstream란?
C++의 <sstream> 헤더 파일은 문자열을 스트림으로 다루기 위한 기능을 제공합니다
헤더 파일은 문자열을 파싱하고 문자열과 다른 데이터 유형 간의 변환을 수행하는 데 사용됩니다
<sstream> 헤더 파일에는 stringstream 클래스와 관련된 기능들이 정의되어 있습니다
이 클래스는 문자열을 스트림으로 취급하여 입출력 연산을 수행할 수 있게 해줍니다
간단한 개념코드로 일단 봅시다
개념 코드
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
// 숫자를 스트림에 쓰기
int num = 42;
ss << num;
// 스트림에서 숫자 읽기
int extractedNum;
ss >> extractedNum;
std::cout << "Extracted number: " << extractedNum << std::endl;
return 0;
}
Explain
위의 코드에서는 std::stringstream 객체 ss를 생성하고 숫자를 스트림에 쓰고 읽어옵니다
<< 연산자를 사용하여 숫자를 스트림에 쓰고 >> 연산자를 사용하여 스트림에서 숫자를 읽어옵니다
이 코드에서는 숫자를 문자열로 저장하고 다시 읽어오는 간단한 기능을 보여줍니다
연습 문제 코드를 이제 봅시다
연습 문제 코드
(문자열을 스트림으로 변환하여 단어 개수 세기)
#include <iostream>
#include <sstream>
#include <string>
int countWords(const std::string& sentence) {
std::stringstream ss(sentence);
std::string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
int main() {
std::string sentence = "This is a sample sentence.";
int wordCount = countWords(sentence);
std::cout << "Number of words: " << wordCount << std::endl;
return 0;
}
Explain
위의 코드는 입력된 문자열에서 단어의 개수를 세는 함수를 구현한 예제입니다
countWords 함수는 문자열을 stringstream으로 변환하고 공백을 기준으로 단어를 추출하여 개수를 세는 기능을 제공합니다
다른 예제 연습 코드를 봅시다
연습 문제 코드
(스트림을 사용하여 숫자 배열 정렬하기)
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
int main() {
std::string numbersString = "5 3 7 1 9";
std::stringstream ss(numbersString);
int num;
std::vector<int> numbers;
while (ss >> num) {
numbers.push_back(num);
}
std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted numbers: ";
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
return 0;
}
Explain
위의 코드는 입력된 숫자들을 스트림으로 읽어와서 벡터에 저장한 후 벡터를 정렬하여 결과를 출력하는 예제입니다 std::sort 함수를 사용하여 숫자들을 오름차순으로 정렬합니다
728x90
LIST