I'm looking to take an IP address (in the form aaa.bbb.ccc.ddd), which I've stored as a string (m_Address), and convert the octets into four integers (m_A, m_B, m_C, m_D). I parsed the string m_Address into four strings, each containing one of the octets (a_string, b_string, c_string, d_string) and am trying to use stringstreams to convert them to ints. The first conversion works (a_string to m_A), but the rest do not. Successive calls to istringstream::str() seem to fail. I'd rather not make four istringstream objects if I don't have to.
Also, is there perhaps an easier way to parse the initial string into the four octets? Thanks to all who help.
int ConvertStringToInt(string m_Address)
//N.B. Code modified for posting purposes.
//Error checking, etc. removed for space and clarity.
//Returns 0 on success, 1 on error.
int count = 0;
string a_string = "";
string b_string = "";
string c_string = "";
string d_string = "";
int m_A, m_B, m_C, m_D;
for(int i = 0; i < m_Address.length(); ++i)
if(count == 0) //aaa
a_string += m_Address[i];
if(count == 1) //bbb
b_string += m_Address[i];
if(count == 2) //ccc
c_string += m_Address[i];
if(count == 3) //ddd
d_string += m_Address[i];
else //Not a digit.
if(m_Address[i] == '.')
//Convert strings to integers.
stream_buffer >> m_A;
stream_buffer >> m_B;
stream_buffer >> m_C;
stream_buffer >> m_D;
/***What I'd like to avoid doing***/
//m_A = atoi(a_string.c_str());
//m_B = atoi(b_string.c_str());
//m_C = atoi(c_string.c_str());
//m_D = atoi(d_string.c_str());
you have to clear() the string stream each time.
however there's a much easier way to do this!
if m_address is "192.168.0.1" (for example) you can simply read it directly out of the stringstream as follows
easy as that.
int oct1, oct2, oct3, oct4;
string addr = "192.168.0.1";
str >> oct1 >> dot >> oct2 >> dot >> oct3 >> dot >> oct4;