Search code examples
c++stringvectoratoi

Saving integers in vector from string


I have this string which contains numbers divided from one another with a /, like this 24/2/13. I want to save them individually in a vector of int,but it gives me this mistake expected unqualified-id before '.' token|. I know it might be a stupid mistake but that's just the qay for now :). Here is the code:


int t;
string s;
for(int i=0;i<final_states.size();i++)
{
    if(final_states.at(i)!='/')
        s.push_back(final_states.at(i));
    else
    {
        t=atoi(s.c_str());
        temp_final_states.push_back(t);
        s.clear();
    }
}

Solution

  • Assuming your string always starts with a numeric value and the '/' character is not at the end of the string this should do it for you:

    std::string final_states="24/2/13";
    std::vector<int> temp_final_states;
    
    temp_final_states.push_back(atoi(final_states.c_str()));
    std::string::size_type index = final_states.find('/');
    
    for (; index != std::string::npos; index = final_states.find('/', index) )
    {
        ++index;
        const char* str = final_states.c_str() + index;
        temp_final_states.push_back(atoi(str));
    }