www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - foreach: How start a foreach count with specific number?

reply Marcone <marcone email.com> writes:
Example:

// --args "C:\Users\Usuario\Downloads\dist\Programa.exe"

import modulo;

void main(string[] args){
	if (args.length >= 2)
	{
		string exePrincipal = args[1];
		chdir(exePrincipal.dirName);
		
		foreach(n, i; glob("*")){
			print("{} DATA {}".format(n, i));
		}
	}
}

This print:

0 DATA icone.ico
1 DATA libgcc_s_dw2-1.dll
2 DATA libstdc++-6.dll
3 DATA libwinpthread-1.dll
4 DATA platforms
5 DATA Programa.d
6 DATA Programa.exe
7 DATA Programa.obj
8 DATA Programa.rc
9 DATA Programa.res
10 DATA Qt5Core.dll
11 DATA Qt5Gui.dll
12 DATA Qt5Widgets.dll
13 DATA qte5.d
14 DATA QtE5Widgets32.dll


But I don't want it starts with 0, but other number. How can I do 
it?
Jun 02 2021
next sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 6/2/21 8:49 AM, Marcone wrote:

 But I don't want it starts with 0, but other number. How can I do it?
It is not configurable but is trivial by adding a base value: import std.stdio; enum base = 17; void main() { auto arr = [ "hello", "world" ]; foreach (i, str; arr) { const count = base + i; writefln!"%s: %s"(count, str); } } Ali
Jun 02 2021
prev sibling parent Paul Backus <snarwin gmail.com> writes:
On Wednesday, 2 June 2021 at 15:49:36 UTC, Marcone wrote:
 But I don't want it starts with 0, but other number. How can I 
 do it?
Easiest way is to just add the starting number: size_t start = 5; foreach (n, i; glob("*")) { print("{} DATA {}".format(n, start + i)); } You can also use [`std.range.enumerate`][1], which takes the number to start with as an optional argument: foreach (n, i; glob("*").enumerate(5)) { print("{} DATA {}".format(n, start + i)); } [1]: https://phobos.dpldocs.info/std.range.enumerate.html
Jun 02 2021