1. Get IP from user in this format xx.xx.xx.xx
2. Fill zeros at the left of each segment if user did not enter 3 digits on the set, e.g.
0xx.00x.xxx.0xx
Input is: 22.3.120.32
Output should be: 022.003.120.032
Here is my code, it works but not perfectly. When user inserts 111.33.66.3, nothing happens, it works when the first segment is not 3 numbers, there are many other flaws too.
Do you have a better algorithm? Please note that i will receive the IP from a parameter ready & then pass it to a function that inserts zeros on the front if possible. The piece of code above is a sample out of a bigger source code.
You can use boost::regex to split the input into the 4 octets, then use boost::format to add leading zeroes.
Or use scanf to with the format string "%u.%u.%u.%u", read into four unsigneds, then use printf with the format string
"%03u.%03u.%03u.%03u" to output with the leading zeroes.
Or you can use string.find() to find the positions of the dots and insert zeroes so that each dot is exactly 4 positions away from the previous.