以D语言从控制台读取输入时出错
我正在写一个简单的代码来输入要带到派对上的糖果和气球的数量。 我写过以D语言从控制台读取输入时出错,d,stdin,D,Stdin,我正在写一个简单的代码来输入要带到派对上的糖果和气球的数量。 我写过 import std.stdio; void main() { int candiesCount; readf("%s", &candiesCount); write("How many balloons are there? "); int balloonCount; readf("%s", &balloonCount); writeln("Got it: There are ", candiesCo
import std.stdio;
void main()
{
int candiesCount;
readf("%s", &candiesCount);
write("How many balloons are there? ");
int balloonCount;
readf("%s", &balloonCount);
writeln("Got it: There are ", candiesCount, " candies",
" and ", balloonCount, " balloons.");
}
但在输入糖果数量后,我得到以下错误:
Unexpected '
' when converting from type LockingTextReader to type int
----------------
0x00403B5F
0x004038FF
0x004033AE
0x00402564
0x004024C0
0x00402415
0x0040206A
0x7564173E in BaseThreadInitThunk
0x77C76911 in LdrInitializeThunk
0x77C768BD in LdrInitializeThunk
请帮助我,因为我不熟悉这门语言。这也让我有一段时间感到困惑。Andrei解释说,
readf
是关于与格式字符串匹配的输入
您只需在格式字符串的末尾添加\n
。我认为这是因为您按enter键提交输入,但我不完全确定(我对这种语言还是新手)
它应该是这样的:
readf("%s\n", &candiesCount);
...
readf("%s\n", &balloonCount);
这也让我困惑了一段时间。Andrei解释说,
readf
是关于与格式字符串匹配的输入
您只需在格式字符串的末尾添加\n
。我认为这是因为您按enter键提交输入,但我不完全确定(我对这种语言还是新手)
它应该是这样的:
readf("%s\n", &candiesCount);
...
readf("%s\n", &balloonCount);
由于输入不匹配而发生错误。原因是空格。要解决这个问题,请使用
readf(" %s", &candiesCount); // notice the space before %s
在%s
前面添加空格将跳过空白字符
有关更多详细信息,请查看此页面(出于某种原因,该页面恰好有一个与您非常相似的示例):由于输入不匹配而发生错误。原因是空格。要解决这个问题,请使用
readf(" %s", &candiesCount); // notice the space before %s
在%s
前面添加空格将跳过空白字符
有关更多详细信息,请查看此页面(出于某种原因,该页面碰巧有一个与您非常相似的示例):