Hi and welcome.
Your sketch is not waiting for any characters to be received. If no characters are available it just keeps printing a random number, because it gets to the end of your getanswer() function without executing a return command. Even if there is a character to receive, it does not wait for the remaining characters to complete the number typed. There are quite a few other errors also, but lets take them one at a time. Have a look at while().
Also forum etiquette is that when you post a sketch here, you should always use code tags (the # button). It prevents long sketches from filling the screen, and stops certain character sequences used in sketches from getting turned into smileys! Code tags do this:
void setup()
{
Serial.begin(9600);
}
void loop()
{
long length=getanswer(0);
Serial.print(length);
}
long getanswer(int totallength)
{
if(Serial.available())
{
int number;
char ch=Serial.read();
if(isDigit(ch))
{
number=(number*10)+(ch-48);
}
else if(ch==10)
{
totallength=number;
return totallength;
}
}
}
Paul