I am writing an IP calculator program to convert an IP adress into the broadcast adress, network adress etc.
I need to convert the adress into 8-digit biniary first, I already used itoa
for it decimal to biniary conversion, but I still need to make it always 8 digit.
I want to use a switch
to do it. First the program counts the number of digits in the binary form, and then, using switch
(I put it into a comment, I need to figure out this proble first) and if
it adds enough zeros in front of the number (actually a string at this point) so it would always be 8 characters long.
I want to use string e1('00',e);
instruction to add two zeros to the string, but it doesn't work. e
is the original string, e1 is the new 8 character string. It doesn't want to compile, stops at this line (string e1('00',e);
) and gives:
error: no matching function for call to 'std::__cxx11::basic_string<char>:: basic_string(int, std::__cxx11::string)'|
My code:
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
/**
* C++ version 0.4 std::string style "itoa":
* Contributions from Stuart Lowe, Ray-Yuan Sheu,
* Rodrigo de Salvo Braz, Luc Gallant, John Maloney
* and Brian Hunt
*/
std::string itoa(int value, int base)
{
std::string buf;
// check that the base if valid
if (base < 2 || base > 16)
return buf;
enum
{
kMaxDigits = 35
};
buf.reserve(kMaxDigits); // Pre-allocate enough space.
int quotient = value;
// Translating number to string with base:
do
{
buf += "0123456789abcdef"[std::abs(quotient % base)];
quotient /= base;
} while (quotient);
// Append the negative sign
if (value < 0)
buf += '-';
std::reverse(buf.begin(), buf.end());
return buf;
}
int main()
{
cout << "Dzien dobry." << endl
<< "Jest OK!\n";
int a, b, c, d, i, j, k, l, m, n, o, p, r, s, t, u, w, v, x, y, z;
cout << "Wprowadz pierwszy oktet: ";
cin >> a;
cout << "Wprowadz drugi oktet: ";
cin >> b;
cout << "Wprowadz trzeci oktet: ";
cin >> c;
cout << "Wprowadz czwarty oktet: ";
cin >> d;
cout << "Wyswietlam adres IP w postaci dziesietnej: " << a << "." << b << "." << c << "." << d << "\n";
char res[1000];
itoa(a, res, 2);
string e(res);
itoa(b, res, 2);
string f(res);
itoa(c, res, 2);
string g(res);
itoa(d, res, 2);
string h(res);
//
x = e.size();
cout << x << "\n";
/*
if (x<8)
{
switch(x)
{
case 1: string e(1);
break;
case 2: string e(3);
break;
case 3: string e(2);
break;
case 4: string e(0);
break;
case 5: string e(4);
break;
case 6: string e(7);
break;
case 7: string e(0);
break;
default: cout << "error";
}
}
*/
string e1('00', e);
cout << e1 << "\n";
cout << "Wyswietlam adres IP w postaci dwojkowej: " << e1 << "." << f << "." << g << "." << h;
return 0;
}