I need some help..

• 05-16-2003
FromHolland
I need some help..
I am going to create my first real(tiny) program.
It will be a hexadecimal converter and it can be used to convert a value between 0 and 255 to a hexadecimal value.

Example:

normal -- hex

7 -- 7
143 -- 8f
211 -- d3
255 -- ff
etc..

For examle: When a user inputs '211', the program should return a string containing 'd3'. The program will be used to convert
hexadecimals in order to get color values used by games like Warcraft 3. The user must enter 3 values between 255 and 0, so the program will return a 6 digits hexadecimal value.

Like this:

User input: == Program returns:
255-155-55 == ff-9b-37

ONE way to do this, is by making a long, long IF statement (255)
in order to let the program return the desired value.

Due to my lack of programming experience I would like someone to tell me if there is a more efficient way..
• 05-16-2003
Brighteyes
>For examle: When a user inputs '211', the program should return a string containing 'd3'.
>I would like someone to tell me if there is a more efficient way..
Yes, there is. :)
Code:

```#include <iostream> #include <iomanip> #include <sstream> #include <cstdlib> using namespace std; /*  *  Decimal => Hexadecimal converter  *  Copyright (c) Liz Guth 2003  */ int main() {     long decimal;     cout<<"Enter a number: "<<flush;     if (!(cin>> decimal))     {         cerr<<"Whoops, invalid input";         exit(EXIT_FAILURE);     }     ostringstream convert;     convert<< hex << decimal;     cout<<"Your number, "<< decimal <<", is "         << convert.str() <<" in hexadecimal."<<endl; }```
• 05-16-2003
FromHolland
I didn't know there were 'decimal' functions..
Well, I see it's not that complex. But what is this
{
cerr<<

thing?
• 05-16-2003
Brighteyes
If the user doesn't type a number, or something freaky happens, a message is printed on the error stream and the program terminates. cerr is like cout except that it typically isn't buffered, good for error messages.
• 05-16-2003
DougDbug
Something to keep in mind...
Conversion between bases only takes place during input or output. All variables are stored in binary. You can't save a number in hex. So, I don't usually use the word "convert"... I might say something like "Input as hex and display in octal format".

Of course, true conversion does take place when when you convert an ASCII string to a number.

cin and cout can use decimal, octal, or hex directly. There is a function strtoul() [string to unsigned long] that can handle input from base 2 to base 36. There is bitset (From the Standard Template Library) which can handle binary. Displaying output in "weird" bases can be more difficult, although microsoft includes the non-standard _itoa() [Integer To ASCII] function.

BTW- "I neeed some help" is a vague title. Please try to say what the topic of your question is.Board Guidelines