Dynamic array and foreach loop

Binarydepth via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 8 11:24:46 PDT 2015


On Saturday, 8 August 2015 at 17:19:08 UTC, DarthCthulhu wrote:
> You can fix it like the following:
>
> foreach(num, element; liaOrig)	{//Data input loop
> 		
> 			writefln("num: %s current element: %s liaOrig.length: %s", 
> num, element, liaOrig.length);
>
> 			write("Input the element : ", num+1, " ");
> 			readf(" %d", &liaOrig[num]);
> 		}
>
> Now 'num' is just an iterative number starting from 0 (the 
> .init value of an int), while the actual element value is  
> stored in 'element'. I added the writefln() statement to make 
> it a bit more clear during runtime.
>
> As an addenum, you don't need the liaOrig[0 .. $] in the 
> foreach statement; just the name of the array variable is 
> required to walk the entire array.
>
> Hope this helps!

Thanks that fixed it. I just realized that I'm doing it wrong. 
This is the new code :

	foreach(num; 0..liEle)	{//Data input loop

		write("Input the element : ", num+1, " ");
		readf(" %d", &liaOrig[num]);
	}


More information about the Digitalmars-d-learn mailing list