【问题标题】:Getting a "terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): invalid UTF-8 byte at index 0: 0x81"获得“在抛出 'nlohmann::detail::type_error' what() 实例后调用的终止:索引 0:0x81 处的无效 UTF-8 字节”
【发布时间】:2020-10-15 03:56:22
【问题描述】:

我正在处理一个网站上的编码问题,当我编译我的代码时,它给了我:

在抛出一个实例后调用终止 'nlohmann::detail::type_error' 什么(): [json.exception.type_error.316] 索引 0 处的无效 UTF-8 字节:0x81 中止退出状态 134

但是,当我在 Sublime 上编译时,它可以正常输出正确的输出。我使用 ASCII 值存储到字符串变量answer 的方式有什么问题吗?这是我的代码:

string caesarCypherEncryptor(string str, int key) {
    string answer = "";
    for(char letter : str) {
        // if it goes over 'z': get amount pass 'z' and start at 'a'
        if(letter + key > int('z')) {
            // push back char into answer string
            answer += ((letter + key) % int('z') + int('a'));  
            continue;
        }
        // else just add key from current position
        answer += letter + key; 
    }
    return answer;
}

int main() {

    cout << caesarCypherEncryptor("mvklahvjcnbwqvtutmfafkwiuagjkzmzwgf", 7) << endl;

    return 0;
}

【问题讨论】:

  • 但是,当我在 Sublime 上编译时它工作得很好 -- 我没有看到任何程序。我看到了一个功能。 main 函数、样本数据和对该函数的调用在哪里?这不是minimal reproducible example
  • 另外,Sublime 不是 C++ 编译器。它是一个代码编辑器和一个 IDE。
  • char 是有符号还是无符号取决于编译器。有符号整数类型的算术溢出会导致未定义的行为。如果 char 已签名,则例如'z' + 7 将溢出。如果您明确指定无符号(如unsigned char letter),会有什么行为?
  • 我得到了与 unsigned char letter 相同的结果
  • 请再次阅读错误信息。它说什么?从哪里报道?当您有一个不是有效 UTF-8 字符的字符,然后尝试将其作为 UTF-8 字符传递时,您认为会发生什么?请记住,ASCII 字母表是 位编码系统,而 UTF-8 使用 ASCII 作为前 127 个字符。 0x80 以上的字符值作为单个字符无效。

标签: c++ compiler-errors runtime-error


【解决方案1】:

我也遇到过这个问题。 这基本上发生在我们将 int 添加到字符并且最终 ascii 值超过 127 时。结果,ascii 值翻转。即'z' + 7 = 129 - 但它会翻转并变成 - 129 - 127 = 2

基本上你需要使用以下条件:

if((unsigned int)(letter + key) > 'z')

请尝试一下,如果有帮助,请告诉我。

【讨论】:

    【解决方案2】:

    我也试过这个问题,可能在你提到的同一个网站上。 对于将来面临这个问题的任何人来说,问题就在眼前 比较:

    if(letter + key > int('z'))
    

    在上面的行中,ascii 值将超过一定的限制,如果 key 大于 26,则 JSON 作为有效字符除外,顺便说一句,这也是无用计算的一部分,因为 key > 26,例如说27 与 key = 1 相同。

    因此,解决方案的第一行应该是 key = (key % 26)。

    这可以防止上面给出的 JSON 异常错误。

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 2019-02-08
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多