【问题标题】:How to make the conversion from 'int' to 'char' reasonable under -Werror=conversion option? c++11如何在 -Werror=conversion 选项下合理地进行从 'int' 到 'char' 的转换? c++11
【发布时间】:2022-01-20 02:18:15
【问题描述】:

error: conversion from ‘int’ to ‘char’ may change value [-Werror=conversion]

构建 cmd 示例: g++ -std=c++11 test.cpp -o a.out -Werror=conversion

    auto index = 3;
    char singleChar = 'A' + index; // I want to get A-Z

我希望 sigleChar 是动态分配的。 你能帮我在不使用开关的情况下解决这个错误报告吗? 怎么写代码比较好?

【问题讨论】:

  • char singleChar = static_cast<char>('A' + index);
  • 您假设大写字母是一组连续的值('B' == 'A' + 1、'C' == 'B' + 1 等)。 C++ 标准不保证这样的事情——而且现实世界的标准化字符集是不正确的。 char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index] 或(由于指针算法的交换性)index["ABCDEFGHIJKLMNOPQRSTUVWXYZ"] 可能更简单。

标签: c++ algorithm char integer c++17


【解决方案1】:

'A' + index; // I want to get A-Z 仅适用于 ASCII,例如不适用于 EBCDIC。

一种更便携的解决方案(不涉及 int 到 char 的转换)是数组索引:

char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];

【讨论】:

  • 嗨,Jarodr42,看起来不错!但我还有一个问题,你能帮帮我吗?如果我无法控制索引的值。如果索引大于 25,如何更合适地编写代码?
  • 不确定您对超出界限值的期望是什么? index % 26 可能会确保您在绑定中。
  • 谢谢!如果索引来自字符串。如何确保索引在范围内?还是我应该报告错误? std::string name="my12"; // 可以是 "myxx" auto size = name.size();自动索引 = std::stoi(name.substr(2, size)); char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index%26];
  • 错误处理由您决定。可能,if (index < 0 || 26 <= index) throw std::out_of_range("!").
  • 如果index 为负数,index%26 将不在界限内。
【解决方案2】:

您必须将其类型转换为char:

auto index = 3;
char singleChar {static_cast<char>('A' + index)};

【讨论】:

  • 那真是太好了!
  • 嗨,如果我想保存为函数,我应该添加 try-catch 吗? char fun(int index){ try{ char singleChar = static_cast('A' + index); } catch (std::exception& e) { std::cerr
  • @Mr.Zhang try 块中的这个表达式永远不会抛出异常。异常处理完全没有必要。
  • 我的意思是如果好玩(256)
猜你喜欢
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2014-12-04
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多