Search code examples
d

D lang - Using read and readln() in the same program


I'm having a very strange issue with a D program. read(" %s", variable) works fine by itself and readln(variable) works fine by itself, but when I put the two together, readln() appears to be passed over. The error occurred using both gdc and dmd.

import std.stdio;
import std.string;

void main()
{
    int x;
    write("Enter a number: ");
    readf(" %s", &x);

    write("What is your name? ");
    string name=chomp(readln());

    writeln("Hello ", name, "!");
}

Output:

Enter a number: 5
What is your name? Hello !

However, if I comment out readf(" %s", &x), readln is called as I desire:

Enter a number: What is your name? hjl
Hello hjl!

Solution

  • This is a common mistake with the readf and scanf function from C too. readf is pretty exact about the format string and whitespace. With your string there, it reads the value then stops at the first whitespace it sees... which happens to be the newline.

    If you were to do this:

    Enter a number: 123 bill
    

    It would print What is your name? Hello bill! because it stopped at the space, then readln picked that up until end of line.

    If you do 123, hit enter, then enter your name, readf stops at the newline character... which readln then picks up as an empty line.

    Easiest fix is to just tell readf to consume the newline too:

    readf(" %s\n", &x);
    

    Then readln will be starting with an empty buffer and be able to get what it needs to get.