Sometimes, we need to use IP Address in three digits and we don’t want to input zeros with the digits, this C++ program will pad each octets of an IP Address with Zeros.
Consider the program:
#include<iostream> using namespace std; #include <stdio.h> #include <string.h> #include <stdlib.h> void padZeroIP(char *str) { int oct1=0; int oct2=0; int oct3=0; int oct4=0; int CIDR = 0; int i = 0; const char s[2] = "."; char *token; /* get the first token */ token = strtok(str, s); oct1 = atoi(token); /* walk through other tokens */ while( token != NULL ) { token = strtok(NULL, s); if(i==0) oct2 = atoi(token); else if(i==1) oct3 = atoi(token); else if(i==2) oct4 = atoi(token); i++; } sprintf(str,"%03d.%03d.%03d.%03d",oct1,oct2,oct3,oct4); } //main program int main() { char ip[]="192.168.10.43"; cout<<endl<<"IP before padding: "<<ip; padZeroIP(ip); cout<<endl<<"IP after padding: "<<ip; cout<<endl; return 0; }
Output
IP before padding: 192.168.10.43 IP after padding: 192.168.010.043
In above function we used strtok() function to tokenize IP address by dot (.) operator and then save each octets in 3 bytes padded with zeros.
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Consider the program:
Output
In above function we used strtok() function to tokenize IP address by dot (.) operator and then save each octets in 3 bytes padded with zeros.
need an explanation for this answer? contact us directly to get an explanation for this answer