从字符串类型转换为 int 类型同时将用户输入从字符串转换为 int 时出现意外的 '\n'

pro*_*ter 0 string variables d dmd

当我编译我用dlang编写的代码时出现一个神秘的错误,它显示

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

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

这是我写的代码-

import std.stdio;
import std.conv;

void main()
{
    string a = readln();
    auto b = to!int(a);
}
Run Code Online (Sandbox Code Playgroud)

这是产生的完整错误 -

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
Run Code Online (Sandbox Code Playgroud)

Web*_*001 5

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

要清理干净,你可以使用replace在CircuitCoder的答复中提到,然而,标准库提供更快/更有效(不分配)方法正是这个用例:chomp1):

import std.string : chomp;

string a = readln().chomp; // removes trailing new-line only
int b = a.to!int;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

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