Reading whitespace separated strings from stdin?

weaselcat via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 20 20:44:15 PDT 2015


On Tuesday, 21 April 2015 at 01:31:58 UTC, TheGag96 wrote:
> Hi guys! I had this homework assignment for data structures 
> that has a pretty easy solution in C++. Reading input like 
> this...
>
> 1 2 3 # $
> 4 3 * ! #
> 20 3 / # $ #
> 62 # $
> 2 3 8 * + #
> 4 48 4 2 + / #
> SUM # $
> 1 2 3 4 5 #
> R #
> @
>
> ...where "@" denotes the end of input is fairly simple in C++:
>
> string token = "";
> while (token != "@") {
>   //handle input
> }
>
> Note that having newlines doesn't matter at all; every token is 
> just assumed to be separated by "whitespace". However in D, I 
> looked around could not find a solution better than this:
>
> foreach (line; stdin.byLine) {
>   foreach (token; line.split) {
>     //handle input
>   }
> }
>
> Is there any way to do this without two loops/creating an 
> array? "readf(" %d", &token);" wasn't cutting it either.
>
> Thanks.

import std.stdio;
import std.array;
void main(){
     auto tokens = stdin.readln('@').split;
     writeln(tokens);
}

["1", "2", "3", "#", "$", "4", "3", "*", "!", "#", "20", "3", 
"/", "#", "$", "#", "62", "#", "$", "2", "3", "8", "*", "+", "#", 
"4", "48", "4", "2", "+", "/", "#", "SUM", "#", "$", "1", "2", 
"3", "4", "5", "#", "R", "#", "@"]


More information about the Digitalmars-d-learn mailing list