I'm having some issue in it
I prefer std::stringstream. The 3rd parameter to std::getline() is a delimiter value, and seems to fit this challenge nicely.
In the following code, I extract each field as a string, and push it into a vector of strings (addrFields).
To report results, I list the fields, then output again with the fields converted to ints with std::stoi().
Note: I append the '.' delimeter to the address ... this trivially avoids the eof() truncating the last field.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cassert>
int exec()
{
std::string address ("172.16.524.1");
std::cout << "\n\n echo of input: '" << address << "'" << std::endl;
std::vector<std::string> addrFields;
{
// fill ss with the address vvv append one delim
std::stringstream ss(address + '.');
std::cout << " ss contents: '" << ss.str()
<< "'" << std::endl;
do // loop through fields
{
std::string f;
(void)std::getline(ss, f, '.'); // each field ends at delim
if (false == ss.good())
{
if (ss.eof()) break; // quietly exit, a normal op
// something wrong with input
std::cerr << "\n err Line: " << address << std::endl;
assert(0); // no use continuing with bad input
}
if(f.size()) // ignore blank fields
addrFields.push_back(f);
// consider using addrFields.size()
// for special handling 4 or 6 fields
// for special handling of a colon appended port num
} while(true);
}
std::cout << "\n Results " << std::endl;
std::cout << "\n addrFields : ";
for (auto f : addrFields)
std::cout << f << " ";
std::cout << " (strings) "
<< "\n\n addr ints : ";
for (auto f : addrFields)
std::cout << std::stoi(f) << " ";
std::cout << " (converted to ints) " << std::endl;
return 0;
}
Output is:
echo of input: '172.16.524.1'
ss contents: '172.16.524.1.'
Results
addrFields : 172 16 524 1 (strings)
addr ints : 172 16 524 1 (converted to ints)