www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Recursive function call

reply "Suliman" <evermind live.ru> writes:
string getFileName()
{
	//чтобы было проще обрабатываемый файл
будем хранить рядом с 
бинариком
	string filename = chomp(readln());
	string path = getcwd();
	writeln((path ~ "\\" ~ filename));
	if (exists(path ~ "\\" ~ filename))
		return (path ~ "\\" ~ filename);
	else
	{
		writeln("File do not exists. Please try again");
		getFilename(); //I need something similar, to call function 
again.
	}
	
}


In case of error, how I can call function getFileName again?
Sep 24 2014
next sibling parent "Marc =?UTF-8?B?U2Now7x0eiI=?= <schuetzm gmx.net> writes:
How about using a loop?

     string getFileName() {
         while(true) {
             string filename = chomp(readln());
             string path = getcwd();
             writeln((path ~ "\\" ~ filename));
             if (exists(path ~ "\\" ~ filename))
		return (path ~ "\\" ~ filename);
             writeln("File do not exists. Please try again");
	}
     }
Sep 24 2014
prev sibling next sibling parent "monarch_dodra" <monarchdodra gmail.com> writes:
On Wednesday, 24 September 2014 at 10:57:27 UTC, Suliman wrote:
 string getFileName()
 {
 	//чтобы было проще обрабатываемый файл
будем хранить рядом с 
 бинариком
 	string filename = chomp(readln());
 	string path = getcwd();
 	writeln((path ~ "\\" ~ filename));
 	if (exists(path ~ "\\" ~ filename))
 		return (path ~ "\\" ~ filename);
Don't do `path ~ "\\" ~ filename`. Instead, use "std.path.buildPath". It's more portable, faster, and convenient. Also, you should store the result in a named variable, or you'll reallocate a new string everytime.
 	else
 	{
 		writeln("File do not exists. Please try again");
 		getFilename(); //I need something similar, to call function 
 again.
 	}
 	
 }


 In case of error, how I can call function getFileName again?
Any kind of looping control structure would work. I'd advocate the while(1) loop with a break or return: while(1) { string filename = chomp(readln()); string path = getcwd(); string fullPath = buildPath(path, filename); if (exists(fullPath)) return fullPath; writeln("File does not exists. Please try again"); }
Sep 24 2014
prev sibling parent "anonymous" <anonymous example.com> writes:
On Wednesday, 24 September 2014 at 10:57:27 UTC, Suliman wrote:
 string getFileName()
 {
[...]
 		getFilename(); //I need something similar, to call function 
 again.
You mistyped the function name, it's getFileName (capital N), and you forgot "return". So: return getFileName();
Sep 24 2014