Reading a line from stdin

Ali Çehreli acehreli at yahoo.com
Tue Mar 15 22:05:37 PDT 2011


I am going over some sample programs in a text of mine and replacing 
std.cstream references with std.stdio. There are non-trivial differences 
with formatted input.

The following program may be surprising to the novice:

import std.stdio;

void main()
{
     write("What is your name? ");
     string name = readln();
     writeln("Hi ", name, "!");
}

The newline character is read as a part of the input:

What is your name? Ali
Hi Ali
!       <-- this is outputted on the next line
             because of the newline character

A solution is to strip the line after reading:

import std.string;
// ...
     string name = strip(readln());

Right? Is there a better way that I am missing?

Thank you,
Ali


More information about the Digitalmars-d-learn mailing list