0

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

5
  • numbers don't deal with leading zeroes. You sure you can't use a string? Commented Feb 14, 2022 at 3:32
  • If you know the length of the digit, you can use for-loop with % operator. Commented Feb 14, 2022 at 3:37
  • yes sorry, actually read it and save as string, I transformed it to int because I thought it was the first step Commented Feb 14, 2022 at 3:44
  • Is Vec[0] the most significant digit from your string? Or your least significant? Hard to tell with that palindrome you got there. Commented Feb 14, 2022 at 4:16
  • Think of the advantages of leaving it a string. It's already chopped up into digits, no math is needed to split it up, you just need to iterate the characters. Commented Feb 14, 2022 at 4:35

1 Answer 1

1

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

#include <string>
#include <vector>

int main(){
    using namespace std;
    string number = "0110";
    vector < int > Vec;
    for(char& digit : number){
        Vec.push_back(digit - '0');
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Your code would not compile due to omitting namespace std
@Slava Oh, You are right, I will add it ASAP.
If at all, it's better to put using namespace std inside main.
@MichaelChourdakis You are right. but as this code is for just demonstration purpose, as long as it compiles, it is up to the user to modify it for their needs.
"as long as it compiles, it is up to the user to modify it for their needs" I think it is better not to propagate bad habits in answer as it can be used by novice programmers as recommendations of code writing style.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.