【问题标题】:Unexpected '\n' when converting from type string to type int while converting user input to int from string在将用户输入从字符串转换为 int 时,从字符串类型转换为 int 类型时出现意外的“\n”
【发布时间】:2021-06-02 10:41:05
【问题描述】:

我在编译我用 dlang 编写的代码时遇到一个神秘的错误,它显示

“从 string 类型转换为 int 类型时出现意外的 '\n'”

我在 google 上查了一下,但没有找到解决方案(因为 d 不是一种流行的编程语言)。

这是我写的代码-

import std.stdio;
import std.conv;

void main()
{
    string a = readln();
    auto b = to!int(a);
}

这是产生的完整错误-

std.conv.ConvException@/usr/include/dmd/phobos/std/conv.d(1947): Unexpected '\n' when converting from type string to type int
----------------
/usr/include/dmd/phobos/std/conv.d:85 pure @safe int std.conv.toImpl!(int, immutable(char)[]).toImpl(immutable(char)[]) [0x562507a98a0f]
/usr/include/dmd/phobos/std/conv.d:223 pure @safe int std.conv.to!(int).to!(immutable(char)[]).to(immutable(char)[]) [0x562507a9760f]
source/app.d:11 _Dmain [0x562507a95d34]
Program exited with code 1

【问题讨论】:

    标签: string variables d dmd


    【解决方案1】:

    问题在于readln() 返回用户输入包括行终止换行符(\n\r\n\r 或可能更奇特的字符)和std.conv to 函数在发现意外空白时抛出。您可以简单地取一个不包括最后一个字节的切片,但是当输入结束时没有换行符(即从文件读取或按 Ctrl-D 时文件结束作为用户)它不会包含终止换行符并给你错误的数据。

    要清理它,您可以使用 CircuitCoder 的回答中提到的replace,但是标准库为此用例提供了更快/更有效(无分配)的方法:chomp (1 ):

    import std.string : chomp;
    
    string a = readln().chomp; // removes trailing new-line only
    int b = a.to!int;
    

    chomp 总是删除一个尾随换行符。 (对于\r\n,字符= 可能是多个字节)因为D 中的字符串只是数组——即ptr + length——这意味着chomp 可以有效地为您提供另一个长度减一的实例,这意味着堆上没有内存分配或复制整个字符串,因此您将避免在程序后期进行潜在的 GC 清理,如果您阅读很多行,这将特别有用。

    或者,如果您不关心用户提供给您的 精确 输入,而是希望从输入的开头和结尾完全删除空格(包括换行符) ), 你可以使用strip (2):

    import std.string : strip;
    
    string a = readln().strip; // user can now enter spaces at start and end
    int b = a.to!int;
    

    一般来说,这两个函数对于您正在执行并想要清理的所有用户输入都很有用。

    【讨论】:

      【解决方案2】:

      https://dlang.org/phobos/std_array.html#.replace 导入std.string 并使用readln().replace("\n", ""); 而不仅仅是readln()。这个错误真的没有那么神秘。

      【讨论】:

      • 我的真实代码与我真实代码库中的这个迷你版本完全不同,它是 g 替换了代码中的 a,我只是为了改变它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2022-10-02
      相关资源
      最近更新 更多