-
March 6th, 2009, 06:35 AM
#1
How Can I Insert Zeros in the Middle of a String of IP? C/C++
I wrote a piece of code that does the following:
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.
Here is my code
Code:
#include <iostream>
#include<string>
using namespace std;
const int MAX_IP_SIZE = 15;
const int MAX_IP_DIGIT = 3;
int main ()
{
string IP;
int numOfZerosToFill = 0;
int tempDigitCount = 0;
int IPCurrentPointer = 0;
cout<<"ENTER IP: ";
cin>>IP;
while (IPCurrentPointer < (int)IP.length())
{
char dot = IP.at(IPCurrentPointer);
if(dot == '.')
{
numOfZerosToFill = MAX_IP_DIGIT - tempDigitCount;
if( numOfZerosToFill == 1 || numOfZerosToFill == 2)
{
int spotForFillingZeros = IPCurrentPointer - tempDigitCount;
IP.insert(spotForFillingZeros, numOfZerosToFill, '0');
IPCurrentPointer += numOfZerosToFill;
tempDigitCount = 0;
}
}
else
tempDigitCount++;
IPCurrentPointer++;
}
numOfZerosToFill = MAX_IP_DIGIT - tempDigitCount;
if( numOfZerosToFill == 1 || numOfZerosToFill == 2)
{
int spotForFillingZeros = IPCurrentPointer - tempDigitCount;
IP.insert(spotForFillingZeros, numOfZerosToFill, '0');
IPCurrentPointer += numOfZerosToFill;
}
cout<<IP<<"******"<<endl;
system("pause");
return 0;
}
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.
Thanks
-
March 6th, 2009, 06:50 AM
#2
Re: How Can I Insert Zeros in the Middle of a String of IP? C/C++
Use sprintf to format.
Code:
sprintf (strResult, "%03s", strIpSegment);
if IpSegment is '12', strResult will be '012'.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|