Why doesn't readf behave as expected?

import std.stdio; void main(){ int n; while(readf("%d", &n)){ if(n == 11) break; writeln(n); } } 

The first iteration works, and it prints n , but after that readf() never returns.

There is only one line in the documentation explaining readf() :

uint readf (A ...) (in char [] format, A args);

  Formatted read one line from stdin. 

Am I something wrong? or is something wrong with readf() ? I just need to read numbers from standard input.

using: DMD 2.054 64-bit

+6
source share
1 answer

I believe because readf treats spaces differently than scanf in C. You need to read spaces explicitly, so change readf("%d", &n) to readf("%d ", &n) and it should work (hopefully )

Here is a quote from Andrei, who introduced the function:

This is by design. The example works when changing as follows:

import std.stdio;

void main () {
int i, j;
readf ("% s", & i);
readf ("% s", & j);
}

The space in front of the second parameter tells readf to read and skip everything before trying to convert.

I implemented readf to be much more Nazi about spaces than scanf in an attempt to improve its accuracy. Scanf was famously difficult to use for complex analysis and input validation, and I attribute some of them to its non-intervention as relatively blank. I would be happy to soften some of the present if there is sufficient evidence that this serves most of our users. I personally believe that current behavior (strict by default, easy to relax) is best.

http://www.digitalmars.com/d/archives/digitalmars/D/bugs/Issue_4656_New_stdio.readf_does_not_ignore_white_space_24214.html

+9
source

Source: https://habr.com/ru/post/895395/


All Articles