Calling readln() after readf
PinDPlugga
a at a.com
Sat Apr 24 14:46:06 UTC 2021
I didn't want to necropost, but I ran into the same behaviour as
in this post:
https://forum.dlang.org/post/yfybveovbknvvxmioivd@forum.dlang.org
and was just curious to understand it better.
If I call readln() after having previously called readf(), it
does not behave as expected:
```d
import std.stdio, std.string;
void main()
{
write("Please enter a number: ");
double number;
readf(" %s", number);
write("Please enter a string: ");
string input = strip(readln());
writefln!("number: %s --- string: %s")(number, input);
}
```
Gives me the following:
```
Please enter a number: 1
Please enter a string: number: 1 ---- string:
```
I know I can get this to work replacing the `strin(readln())`
with `readf(" %s\n", input)`, but I also found if I just call
`strip(readln())` an extra time this worked as well, but what is
confusing to me is if I have multiple readf's I still only need
to call readln one extra time to get it to work as expected:
```d
import std.stdio, std.string;
void main()
{
write("Please enter a number: ");
double number1;
readf(" %s", number1);
write("Please enter a number: ");
double number2;
readf(" %s", number2);
// Handle what should be two \n's from readf?
string input = strip(readln());
// Continue as normal
write("Please enter a string: ");
input = strip(readln());
writefln!("number1: %s --- number2: %s --- string: %s")
(number1, number2, input);
}
```
And this works.
```
Please enter a number: 1
Please enter a number: 2
Please enter a string: hello
number1: 1 --- number2: 2 --- string: hello
```
Could anyone help explain this to me, and also is there a better
way to handle this when wanting to use a mix of readf and readln?
More information about the Digitalmars-d-learn
mailing list