-
String to Vector
How I can place number from a String value of
S1("4545645486465") to a vector Vec.. The trick part is that I have to place 4 digits in each cell of the vector. Example:
string s1("468648578468486846845")
vector<int>Vec
void main()
{
...
...
...
...
}
Vec[0]=4686
Vec[1}=4857
Vec[2]=8468
....Vec[n]
....
Please Help me..
-
Think about this logically.
You need to extract 4 characters, get their numerical value, and push them onto a vector.
Code:
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
std::vector<int> fill_vec(const std::string &input);
int main(int argc, char* argv[])
{
std::string mystr("13345678198734568765");
std::vector<int> returned = fill_vec(mystr);
for (int i = 0; i < returned.size(); i++)
std::cout<<returned[i]<<std::endl;
return 0;
}
std::vector<int> fill_vec(const std::string &input)
{
typedef std::string::size_type st;
std::string temp;
std::vector<int> intvec;
for (st index = 0; index < input.size(); index += 4)
{
for (int i = index; i < index+4; i++)
temp += input[i];
intvec.push_back(atoi(temp.c_str()));
temp.erase();
}
return intvec;
}
It's 3AM
Here's a sloppy, yet functional solution. input must be a multiple of 4.