string Streams

b4failrise ㅣ 2018. 6. 26. 22:47

contents:

1) sstream과 이것의 3가지 타입(istringstream, ostringstream, stringstream)

2) stringstream-Specific Operations

3) iostream interface를 공유하는 fstream, sstream

4) istringstream 사용하기    (Exercises Section 8.3.1 C++ primer)

5) ostringstream 사용하기    (Exercises Section 8.3.2 C++ primer)




sstream header는 내장 메모리 Input/Output 에 대한 3가지 타입을 정의한다; 이 타입들은 마치 문자열이 IO stream인 것처럼, 문자열을 읽거나 문자열을 쓴다


stringstream 은 문자열에 대해 수행하는 stream 클래스이다.

이것은 기본적으로 stream 기반의 메모리 상 IO 연산을 수행한다.

stringstream은 서로 다른 타입을 parse하는데 도움이 된다.


istringstream type은 문자열을 읽는다.

ostrinstream은 문자열을 쓴다.

stringstream은 문자열을 읽고 쓴다.


One common use of this class is to parse comma-separated integers from a string (e.g., "23,4,56").

stringstream-Specific Operations


sstream strm;        strm 은 unbound stringstream이다.

sstream strm(s);    strm 은 sstream. string s의 복사본을 갖고 있음. 이것의 constructor는 explicit이다.

strm.str()            strm이 갖고 있는 string 복사본을 반환

strm.str(s)        string s를 strm에 복사한다. void 반환



※ fstream과 sstream은 iostream으로 인터페이스를 공유하지만, 이 둘은 아무런 관련이 없음에 주의하라.

특히, stringstream에서 open과 close를 사용할 수 없을 뿐만 아니라 fstream에서는 str을 사용할 수 없다.


1) istringstream 사용하기


Example)

As one example, assume we have a file that lists people and their associated phone

numbers. Some people have only one number, but others have several—a home

phone, work phone, cell number, and so on. Our input file might look like the

following:


morgan 2015552368 8625550123

drew 9735550130

lee 6095550132 2015550175 8005550000



Each record in this file starts with a name, which is followed by one or more phone

numbers.


solution)

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
struct PersonInfo {
string name;
vector<string> phones; //phone number는 여러 개 가질 수 있음
};
int main()
{
string line, word;
vector<PersonInfo> people;
while (getline(cin,line)) { //Ctrl+Z로 입력 마침
PersonInfo info; //while문 반복할 때마다 구조체 지속 생성
istringstream record(line);
record >> info.name; // 이 ex에서는 공백으로 구분
while (record >> word) //nested loop for phone numbers
info.phones.push_back(word);
people.push_back(info);
}
for (int i = 0; people.size(); i++)
{
cout << people[i].name << " ";
for (int j = 0; j < people[i].phones.size(); j++)
{
cout << people[i].phones[j] << " ";
}
cout << endl;
}
}
/* ISSUE & PROBLEM
1. EOF 입력하면, 정상 출력 후 segmentation fault 발생
2. while문을 무슨 기준으로 빠져나갈 것인가? -No need
*/



Example)

Input Format

The first and only line consists of n integers separated by commas.

Output Format

Print the integers after parsing it. 

P.S.: I/O will be automatically handled. You need to complete the function only.

Sample Input

23,4,56

Sample Output

23
4
56


solution)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
#include <iostream>
#include <vector>
#include <sstream>
using std::cout;
using std::endl;
using std::cin;
using std::vector;
using std::string;
using std::stringstream;
 
vector<int> parseInts(string str);
int main()
{
    string str;
    cin >> str;
    vector<int> integers=parseInts(str);
 
    for (int i = 0; i < (int)integers.size(); i++)
    {
        cout << integers[i] << endl;
    }
}
vector<int> parseInts(string str)
{
    int num;    //서로 다른 타입을 한 번씩 저장하기 위한 용도
    char ch;
    vector<int> _integers;    //int타입만 저장되는 vector
    stringstream ss(str);
 
    while (ss >> num)
    {
        _integers.push_back(num);
        ss >> ch;
    }
    
    return _integers;
}
/* NOTE
1. sstream >> Variable 을 수행할 때, 값의 타입과 변수의 타입이 같아야만 대입이 된다.
2.The while(ss >> num) checks, if it actually did work. If the string is empty 
    (I'm not sure with C++ but in C, strings terminate with an invisible character \0), 
    or if the next thing is not a number, then the test fails, and while skips the rest.
*/
cs


'객체 지향 설계' 카테고리의 다른 글

Operator Overloading, Operator Conversions  (0) 2018.06.28
Class  (0) 2018.06.27
Knowing Your Objects: this Pointer 2.  (0) 2018.02.25
Knowing Your Objects: this Pointer 1.  (0) 2018.02.25
static Class Members  (0) 2018.02.25