상세 컨텐츠

본문 제목

Int to string, string to char* in c++

c++

by Riella 2020. 7. 19. 20:47

본문

728x90
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    char* arr [10];
    int count = 0;
    string inp;
    //stringstream ss; <- this will accumulate the numbers
    do {
        stringstream ss;
        ss << count;
        inp = ss.str();
        //cout << "1:" << inp << endl;
        inp.append(" is ");
        //cout << "2:" << inp << endl;
        inp.append((count%2 == 1) ? "odd" : "even");
        //cout << "3:" << inp << endl;
        vector<char> writable(inp.begin(), inp.end());
        writable.push_back('\0');
        arr[count] = &writable[0];
        cout << arr[count] << endl;
        count++;
    } while (count < 10);
    return 0;
}

Part I: I used stringstream to convert int into string.

//#include <sstream>
stringstream ss;
ss << count;
inp = ss.str();

Part II: I appended the string using ternary if condition.

inp.append(" is ");
inp.append((count%2 == 1) ? "odd" : "even");

Part III: I used vector to convert the string into char.

//#include <vector>
vector<char> writable(inp.begin(), inp.end());
writable.push_back('\0'); //need to put \0
arr[count] = &writable[0]; //in order to access the existing element

reference: https://hashcode.co.kr/questions/88/stdstring%EC%9D%84-const-char%EB%82%98-char%EB%A1%9C-%EB%B0%94%EA%BE%B8%EB%8A%94-%EB%B0%A9%EB%B2%95

https://stackoverflow.com/questions/27588961/add-an-element-to-an-empty-vector-in-c-why-push-back-works-and-not

관련글 더보기

댓글 영역