Ad

How To Convert String To Vector C++

- 1 answer

I would like to convert an string into a vector, so that it looks like the following:

string number = "0110";
vector < int > Vec; 

with the result:

Vec[0] = 0 
Vec[1] = 1
Vec[2] = 1
Vec[3] = 0

My problem is that the number starts with a 0, so using % doesn't seem to work if i first transform my string to an int

Ad

Answer

I noticed that the question is modified to make it answerable:

#include <string>
#include <vector>
using namespace std;

int main(){
    string number = "0110";
    vector < int > Vec;
    for(char& digit : number){
        Vec.push_back(digit - '0');
    }
}
Ad
source: stackoverflow.com
Ad