check Input

Nafees via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 17 05:03:11 PDT 2017


On Monday, 17 April 2017 at 11:51:45 UTC, dennis wrote:
>
> Hi,
> try to build a little programm, but need to know
> how to check the input.
>
> For example:  input only numbers: 0 - 9 but 1.5 for example is 
> ok.
>
> thanks

How I would do it:
Run a loop, checking if the characters in input are within the 
range (i.e 0-9 and '.' character)
<code>
import std.stdio;
import std.conv : to;
import std.algorithm : canFind;

private bool isNum(string s){
	bool r=true;
	uinteger i;
	for (i=0;i<s.length;i++){
		if (!"0123456789.".canFind(s[i])){
			r = false;
			break;
		}
	}
	return r;
}

void main(){
	string input = readln;
	if (input.isNum){
		float f = to!float(input);
		if (f > 0 && f < 9){
			writeln("Number is in range");
		}else{
			writeln("Out of range");
		}
	}
}



More information about the Digitalmars-d-learn mailing list