Seems like a perfect opportunity to use a class. I don't know your specific implementation but you could probably adapt it or come up with something similar (could probably be improved upon as well ie..another constructor to accept an array of 4 ints, I whipped it up real quick).
OctetAddress.h
Code:
#ifndef OCTETADDRESS_H
#define OCTETADDRESS_H
#include <iostream>
#include <string>
#include <sstream>
using std::cout;
using std::ostringstream;
using std::string;
class OctetAddress {
private:
string octetString;
int octetField[4];
void setOctetString();
public:
OctetAddress( int = 0, int = 0, int = 0, int = 0 );
void setOctet( int = 0, int = 0, int = 0, int = 0 );
string getOctetString() const;
};
OctetAddress::OctetAddress( int a, int b, int c, int d )
{
setOctet( a, b, c, d );
}
void OctetAddress::setOctet( int a, int b, int c, int d )
{
octetField[0] = ( a > 255 || a < 0 ? 0 : a ); //
octetField[1] = ( b > 255 || b < 0 ? 0 : b ); // Ensure values
octetField[2] = ( c > 255 || c < 0 ? 0 : c ); // are in range
octetField[3] = ( d > 255 || d < 0 ? 0 : d ); //
setOctetString();
}
void OctetAddress::setOctetString()
{
ostringstream buildString;
buildString << octetField[0] << "." << octetField[1] << "." << octetField[2] << "." << octetField[3];
octetString = buildString.str();
}
string OctetAddress::getOctetString() const
{
return octetString;
}
#endif
And a simple example how it's easy to provide organized output.
sampleUse.cpp
Code:
#include <iostream>
#include <iomanip>
#include "OctetAddress.h"
using std::cout;
using std::cin;
using std::setw;
using std::left;
using std::endl;
int main()
{
int octet[4];
cout << "Enter 4 ints:" << endl;
for (int n = 0 ; n < 4 ; n++ )
cin >> octet[n];
OctetAddress ipAddress1( octet[0], octet[1], octet[2], octet[3] );
OctetAddress ipAddress2;
cout << setw(16) << left << ipAddress1.getOctetString() << "random text" << endl;
cout << setw(16) << left << ipAddress2.getOctetString() << "random text" << endl;
ipAddress2.setOctet( 192, 168, 0, 1 );
cout << setw(16) << left << ipAddress2.getOctetString() << "random text" << endl;
return 0;
}