Hello jxo,
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
Repeater is correct there is parts of the program the are all wrong. I would say most is in the while loop.
You should read up on "bitset" because you are not using it correctly.
http://www.cplusplus.com/reference/bitset/bitset/bitset/
I also fount that the "setw" and "setfill" are not needed if "bitset" is used correctly. Well "setw" may be OK.
This is what I did to fix what you have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <iomanip>
#include <limits>
#include <bitset>
#include <cctype> // <--- std::stoi().
#pragma warning(disable : 4996) // <--- I need this for old C code like strtok().
int main()
{
char str[100]{ "10-20-30-254-255" }; // <--- Used for testing. Remove the quoted string for normal use Leave the {}s.
char *temp{};
// Uncomment these lines for normal run.
//std::cout << " Enter a String that contains numbers from 0 to 255 (10-20-30): ";
//std::cin >> str;
temp = strtok(str, "-");
while (temp != NULL)
{
std::cout << "\n The equivalent Binary Numbers are: " << std::endl;
std::cout << " " << temp << " => " << std::bitset<8>(std::stoi(temp)) << std::endl; // <--- Changed "str" to "temp". Removed what was not needed.
temp = strtok(NULL, "-");
}
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue";
std::cin.get();
return 0;
}
|
At the beginning of main you should
ALWAYS initialize your variables when defined.
On line 23 notice the changes to the "cout", some for appearance and some because you were using it wrong. "bitset" takes a number not a string.
The last lines of main before the return that you do not have are a replacement for "system("pause");" that it is best not to use. First it will limit your program to windows computers. Second it could leave the program vulnerable to hackers.
Hope that helps,
Andy