Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将字符打印为整数_C++_Formatting_Ostream_Interpretation - Fatal编程技术网

C++ 将字符打印为整数

C++ 将字符打印为整数,c++,formatting,ostream,interpretation,C++,Formatting,Ostream,Interpretation,我想通过控制我的ostream输出char和无符号char是否有基于中使用的技术的建议 模板 结构格式化程序 { 字符c; 格式化程序(Char_c):c(_c){ bool PrintAsNumber()常量 { //在这里实施你的条件 } }; 模板 std::ostream&operator不,没有更好的方法了。更好的方法是采用自定义流操纵器的形式,如std::hex。然后可以关闭和打开整数打印,而不必为每个数字指定整数。但是自定义操纵器对流本身进行操作,并且没有任何操作可以执行您想要的操

我想通过
控制我的
ostream
输出
char
无符号char
是否有基于中使用的技术的建议

模板
结构格式化程序
{
字符c;
格式化程序(Char_c):c(_c){
bool PrintAsNumber()常量
{
//在这里实施你的条件
}
};
模板

std::ostream&operator不,没有更好的方法了。更好的方法是采用自定义流操纵器的形式,如
std::hex
。然后可以关闭和打开整数打印,而不必为每个数字指定整数。但是自定义操纵器对流本身进行操作,并且没有任何操作可以执行您想要的操作。我想您可以编写自己的流,但这比您现在要做的工作多得多


老实说,您最好的选择是查看您的文本编辑器是否具有使
静态\u cast
更易于键入的功能。我想你会经常打字,否则你就不会问了。这样,阅读您的代码的人就可以准确地知道您的意思(即,将字符打印为整数),而不必查找自定义函数的定义。

只是对旧文章的更新。实际的技巧是使用“+”。例如:

template <typename T>
void my_super_function(T x)
{
  // ...
  std::cout << +x << '\n';  // promotes x to a type printable as a number, regardless of type
  // ...
}
模板
void my_super_函数(tx)
{
// ...

std::cout在C++20中,您可以使用:

unsigned char uc = 42;
std::cout << std::format("{:d}", uc); // format uc as integer 42 (the default)
std::cout << std::format("{:c}", uc); // format uc as char '*' (assuming ASCII)
无符号字符uc=42;

std::您是否希望始终将字符打印为整数或取决于条件?我希望它取决于条件(状态)类似于
ios
状态标志。我不理解区分有符号字符和无符号字符的必要性。如果您想将其输出为数字,请先将其转换为int。否则,只需将其打印到操作系统。也许可以为此编写您自己的io操纵器…
您当然意识到您编写了23行代码吗(不包括测试人员)为了能够将字符打印为数字,对吗?这不是有点过分了吗?
template <typename T>
void my_super_function(T x)
{
  // ...
  std::cout << +x << '\n';  // promotes x to a type printable as a number, regardless of type
  // ...
}
template <typename T>
auto promote_to_printable_integer_type(T i) -> decltype(+i)
{
  return +i;
}
unsigned char uc = 42;
std::cout << std::format("{:d}", uc); // format uc as integer 42 (the default)
std::cout << std::format("{:c}", uc); // format uc as char '*' (assuming ASCII)