Thread: String to Vector

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    1

    Question 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..

  2. #2
    Eibro!@Home
    Guest
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. syntax help?
    By scoobygoo in forum C++ Programming
    Replies: 1
    Last Post: 08-07-2007, 10:38 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM