-2

I have a string like this:

string str = "18:10"; 

18 is the minutes and 10 is the seconds. I need to split the string str and store them into two int variables. So essentially like this: int a = 18, int b =10. How do I do that?

JY078
  • 373
  • 8
  • 21

2 Answers2

3

There's a few way to do this, C style (atoi, atof etc). In C++ we'd use std::stringstream from the header sstream.

#include <iostream>
#include <sstream>

template <typename T>
T convertString( std::string str ) {
    T ret;
    std::stringstream ss(str);
    ss >> ret;
    return ret;
}

int main() {
    std::string str = "18:10";
    int minutes,seconds;

    minutes = convertString<int>(str.substr(0,2));
    seconds = convertString<int>(str.substr(3,4));

    std::cout<<minutes<<" "<<seconds<<"\n";
}

Output:

18 10

This, of course, assumes that your string follow this format exactly (same number of integers, seperated by colon..). If you need to use this in a wider context, perhaps you'd be interested in using the std::regex utility instead.

058 094 041
  • 495
  • 3
  • 6
  • I wonder why you have the template? Could this work for other types as well such as `float` and `double`? – smttsp Mar 05 '16 at 05:56
  • @smttsp I believe so, looking at http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/, _"Extracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of val...."_. Correct me if I'm wrong. – 058 094 041 Mar 05 '16 at 05:58
1

Try this code.

#include <string>
#include <sstream>

template <class NumberType, class CharType>
NumberType StringToNumber(const std::basic_string<CharType> & String)
{
    std::basic_istringstream<CharType> Stream(String);
    NumberType Number;
    Stream >> Number;
    return Number;
}

const std::string str("18:10");
const size_t Pos = str.find(':');
const auto Hour = StringToNumber<int>(str.substr(0, Pos));
const auto Minute = StringToNumber<int>(str.substr(Pos + 1, std::string::npos));

I didn't test it. Fix it if there is any error. You have to do error handling if your string may have empty parts for hours or minutes (e.g.; ":10", "18:" or ":").

hkBattousai
  • 10,161
  • 17
  • 68
  • 119