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?
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?
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.
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 ":").
string str = "18:10";
string first_number, second_number;
int position = str.find(':'); // remember thats it is counting from 0
for(int i = 0; i < position; i++){
first_number = first_number + str[i];
}
cout << "first_number: " << first_number << endl;
for(int i = position+1; i < str.length(); i++){ // position+1 beacasue we dont wanna ':' in our string -> second_number
second_number = second_number + str[i];
}
cout << "second_number: " << second_number << endl;