Problem with using readln.

Andrew Edwards via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 29 22:53:09 PDT 2017


On Sunday, 30 April 2017 at 03:20:20 UTC, JV wrote:
> On Sunday, 30 April 2017 at 03:18:04 UTC, Adam D. Ruppe wrote:
>> On Sunday, 30 April 2017 at 03:10:25 UTC, JV wrote:
>>> btw i forgot to add () at readln while editing the post
>>
>> That's not necessary, it doesn't change anything.
>>
>> But readln without arguments returns a string, not an int.
>
> okay?? but how do i return an int?
> tried using what i found in the internet like using stdio.conv; 
> to use toInt() but still shows error

Basically the simplest way would be:

     int val;
     readf("%d", &val);

But if you are dead set on using readln, you will need to parse 
the line to obtain the integer value. The following demonstrates:

     // Scherkl-Nielsen self-important lookup
     template Module(string moduleName)
     {
	mixin("import Module = " ~ moduleName ~ ";");
     }

     void main()
     {
         with(Module!"std.stdio: readln, writeln")
	with(Module!"std.conv: parse")
	{
             string line;
             parse!int((line = readln)).writeln;
	}
     }

Your attempt failed because there is a '\n' character sitting at 
the end of the line read in by readln. It cannot be converted to 
an integer so any attempt to do so will result in an Exception 
being thrown. As was the case with toInt.

-- Andrew



More information about the Digitalmars-d-learn mailing list