简体   繁体   中英

When converting an int to a hex, do we have to convert it to a string or can we keep it a type int? c++

For this Systems I class that I'm in, they are wanting us to take in a number and convert it to hex. I know that I can do it this way:

cin >> std::hex >> x;

But for this program, I want to try and do it after, because of an if statement.

Here is the code that I have.

cout << "Enter an integer value between 0 and 255 for Green: ";
cin >> G;
if (G > 255 || G < 0)
{
    cout << "The number you have entered is bigger than 255 or smaller than 0.";
}
else 
{
    G = std::hex >> G;
}    

Take in a number and convert it to hex.

This satisfies the ask. Reads the decimal number (0 to 255), stores it in an integer. Uses the integer to display both decimal and hex formatting of the value entered.

#include <iostream>
int main() {
    int G;

    while (true)
    {
        std::cout << "Enter an integer value between 0 and 255 for Green: ";
        std::cin >> G;
        if (G > 255 || G < 0)
        {
            std::cout << "The number you have entered is bigger" \
                << " than 255 or smaller than 0.\n";
        }
        else
        {
            break;
        }
    }

    std::cout<< "G is " << G << " in decimal and 0x" << std::hex << G << " in hex.\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM