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.
Code: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(isdigit(m_Address[i])) { if(count == 0) //aaa a_string += m_Address[i]; else if(count == 1) //bbb b_string += m_Address[i]; else if(count == 2) //ccc c_string += m_Address[i]; else if(count == 3) //ddd d_string += m_Address[i]; } else //Not a digit. if(m_Address[i] == '.') ++count; } //Convert strings to integers. istringstream stream_buffer; stream_buffer.str(a_string); stream_buffer >> m_A; stream_buffer.str(b_string); stream_buffer >> m_B; stream_buffer.str(c_string); stream_buffer >> m_C; stream_buffer.str(d_string); 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()); /****************************/ return(0); //Success! }



LinkBack URL
About LinkBacks



Want to add some