Search code examples
dstdin

Error while reading input from console in D language


I am writing a simple code to input the number of candies and balloons to be brought to a party. I have written

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.");
}

but after entering the number of candies I get this error :

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

Pls Help me as I am new to this language.


Solution

  • This stumped me for awhile as well. Andrei explains that readf is very picky about the input matching the format string.

    You just need to add \n to the end your format strings. I think this is because you press enter to submit the input, but I'm not entirely sure (I am still new to this language as well).

    It should look something like this:

    readf("%s\n", &candiesCount);
    ...
    readf("%s\n", &balloonCount);