简体   繁体   English

将 int 转换为十六进制时,我们是否必须将其转换为字符串,还是可以将其保留为 int 类型? c++

[英]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 class,他们希望我们输入一个数字并将其转换为十六进制。 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.但是对于这个程序,我想在之后尝试做,因为有一个if语句。

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.读取十进制数(0 到 255),将其存储在 integer 中。 Uses the integer to display both decimal and hex formatting of the value entered.使用 integer 显示输入值的十进制和十六进制格式。

#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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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