상세 컨텐츠

본문 제목

Stringstream: cuts the string into parts by space

c++

by Riella 2020. 7. 19. 00:54

본문

728x90

Stringstream gets the input of string (line).

Then it cuts based on space.

I used it when getting rows of integer in one line, cut by one number(formatted in string) using stringstream, and changed into int using atoi( [name_of_string].c_str()) using a while loop.

I used atoi( [].c_str) because the version of c++ was below 11.

This is the sample code:

#include <iostream>
#include <string>
#include <sstream> //for stringstream
#include <stdlib.h> //for atoi

using namespace std;

int main()
{
    cout << "Enter row or integers separated by spaces: ";
    string convert_to_int;
    getline(cin, convert_to_int);
    stringstream ss(convert_to_int);

    int intarr[100];
    string str;
    int count = 0;
    int past;
    string result;
    while(ss >> str) {
        int current = atoi( str.c_str() );
        intarr[count] = current;
        if (count != 0) {
            past = intarr[count - 1];
            //result = (past == current) ? "same\n" : "different\n";
            cout << "The number " << past << " and " << current << " are " << ((past == current) ? "same\n" : "different\n");
        }
        count ++;
    }

    return 0;
}

reference: https://www.acmicpc.net/board/view/25973

https://stackoverflow.com/questions/7663709/how-can-i-convert-a-stdstring-to-int

관련글 더보기

댓글 영역