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:
Okay gotcha. Would I use a while function for it wait for the characters?
Because I've used that getanswer() function to input numbers before, I just don't know why I'm having troubles with it now
Maybe you were using the serial monitor, and your sketch had some big delays that allowed the function to work as you thought it should.
Remember, serial comms are slowwwwwww.
zwood14:
Okay gotcha. Would I use a while function for it wait for the characters?
Because I've used that getanswer() function to input numbers before, I just don't know why I'm having troubles with it now
Yes, a loop to wait for some characters to become available. Then another loop to read and deal with each character.
That version of getanswer () can never have worked, not like that anyway.
It is certainly a learning experience to have a go at using Horner's Method to parse integers, but you might want to look at Serial.parseInt().
Also note that the compiler should have given you a warning message about the getanswer() function. Something like "not all code paths return a value". The function should always return a value to the caller. In this case it should have a return statement when Serial.available() is 0 and when ch is not equal to 10.
A common use is to read serial data from the Serial object until the user presses Enter. When that happens, a newline character ('\n') is sent, signaling the end of input. If the longest message is, say, 15 bytes, then:
char myArray[16]; // Need an extra byte for the null character
int numberRead;
// More of your code...
numberRead = Serial.readBytesUntil('\n', myArray, 15);
myArray[numberRead] = '\0';
// more code??
return atol(myArray);
// the rest of your code
This fragment would keep reading the input stream until the newline is read after the user pressed the Enter key. It will read no more than 15 characters. The method returns the number of bytes actually read, so the next statement places a null character at the end of the input stream so you can treat it as a string. You could then use the standard library atol() to convert the ASCII characters to a long.