MrPickle5
MrPickle5

Reputation: 522

How to convert a string to a series of integers?

Making an RPG and want the currency to be represented in platinum, gold, silver and copper. Unfortunately, my professor wants the currency stored as a string (i.e. string class, not cStrings). For example -- 0.1.23.15 would be 0 platinum, 1 gold, 23 silver and 15 copper.

I would just like to know the big idea of how to implement this. For example -- could I use strtok (i.e. I believe this only works on cStrings) or some other C++ function to accomplish this?

Upvotes: 1

Views: 136

Answers (1)

Johnny Mnemonic
Johnny Mnemonic

Reputation: 3922

Here's one solution:

#include <iostream>
#include <sstream>
#include <vector>

using namespace std;


int main()
{
    string str="0.1.23.15",temp;
    stringstream s(str);
    vector<int> v;

    while(getline(s,temp,'.'))
    {
        v.push_back(stoi(temp));
    }

    for(int i: v) cout << i << endl;//C++11 style
    //for(int i=0; i<v.size(); i++) cout << v[i] << endl; //Old school :D
    system("pause");
    return 0;
}

Upvotes: 3

Related Questions