C++ 通过 Cin 获得十六进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13196589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:04:35  来源:igfitidea点击:

Getting hex through Cin

c++hex

提问by Quaker

Why doesn't this code work?

为什么这段代码不起作用?

int x;
cin >> x;

With the input of 0x1aI get that x == 0and not 26.

随着0x1aI get that x == 0and not的输入26

Why's that?

为什么?

回答by sean

I believe in order to use hex you need to do something like this:

我相信为了使用十六进制你需要做这样的事情:

cin >> hex >> x;
cout << hex << x; 

you can also replace hex with dec and oct etc.

您还可以用 dec 和 oct 等替换十六进制。

回答by Karol D

Actually, You can force >>operator to get and properly interpret prefixes 0and 0x. All you have to do is to remove default settings for std::cin:

实际上,您可以强制>>操作员获取并正确解释前缀00x。您所要做的就是删除以下的默认设置std::cin

std::cin.unsetf(std::ios::dec);
std::cin.unsetf(std::ios::hex);
std::cin.unsetf(std::ios::oct);

Now, when you input 0x1a you will receive 26.

现在,当您输入 0x1a 时,您将收到 26。

回答by 0x499602D2

Think of <<and >>when using std::cout/std::cinlike so:

像这样考虑<<>>使用时std::cout/std::cin

std::cout << xmeans get the value fromx

std::cout << x意味着x

std::cin >> xmeans put the value intox

std::cin >> x意味着将值放入x

Notice the directions in which the operators are pointing. That should give you a hint as to what they do when using these functions.

注意操作员所指的方向。这应该会提示您在使用这些函数时会做什么。

The reason that you are getting 0 as a result and not 26 is because std::cinwill parse the all non numeric characters from your input. After all, xis an int, it won't recognize 0xas a part of a hexadecimal number. It would of had the same behavior if the input was 9x2(the result would simply be 9).

结果是 0 而不是 26 的原因是因为std::cin将从您的输入中解析所有非数字字符。毕竟x是一个int,它不会识别0x为十六进制数的一部分。如果输入是9x2(结果将是9),它将具有相同的行为。

回答by Component 10

Your code should read:

你的代码应该是:

int x;
cin >> hex >> x;

By default cinwill expect any number read in to be decimal. Clearly, 0x1ais not a valid decimal and so the conversion cannot take place. To get it to work we have to use the stream modifierhexwhich prompts cinto expect number conversion from hexadecimal rather than decimal.

默认情况下,cin任何读入的数字都是十进制的。显然,0x1a不是有效的小数,因此无法进行转换。为了让它工作,我们必须使用流修饰符hex,它提示cin期望从十六进制而不是十进制进行数字转换。

The 0xprefix is optional in this case so the input 10would be read and stored as decimal 16.

0x在这种情况下,前缀是可选的,因此输入10将被读取并存储为十进制 16。

回答by AlbertFG

#include<iostream>
using namespace std;

int main()
{
    int data[16];
    cout << "enter the 16 hexadecimal numbers\n";
    for(int i = 0;i < 16;i++)
    {
        if(cin >> hex >> data[i])
            cout << "input worked\n";
        else{
            cin.clear();
            cout << "invalid input\n";
        }
    }
}