3

我写了下面的代码,它以十六进制格式输入一个数字并以十进制格式输出:-

#include<iostream>
#include<iomanip>
#include<stdint.h>

using namespace std;

int main()
{
  uint8_t c;
  cin>>hex>>c;
  cout<<dec<<c;
  //cout<<sizeof(c);
  return 0;
}

但是当我输入 c(12 的十六进制)时,输出又是 c(而不是 12)。有人可以解释一下吗?

4

3 回答 3

6

这是因为uint8_t通常是typedeffor unsigned char。所以它实际上读'c'作 ASCII 0x63

改为使用int

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int c;
    cin>>hex>>c;
    cout<<dec<<c<<'\n';
    return 0;
}

程序输出:

$ g++ test.cpp 
$ ./a.out 
c
12
于 2012-12-09T14:16:55.900 回答
4

uint8_t这实际上是一个不幸的副作用unsigned char。因此,当您存储 c 时,它存储 c 的 ASCII 值(十进制 99),而不是数值 12。

于 2012-12-09T14:17:05.653 回答
0

uint8_t是一个别名,unsigned char不幸的是ostream试图将它作为一个字符输出。这已在 C++20 中修复std::format

#include <format>
#include <iostream>
#include <stdint.h>

int main() {
  uint8_t n = 42;
  std::cout << std::format("{}", n);
}

输出:

42
于 2021-03-05T04:32:08.853 回答