Question about Serial.parseInt()

Hello Guys
I am using UNO for learning Arduino.
I want to get integer from Seial

this is the test code

 int age;       //Declare an Int variable to hold your age
 
void setup() {
  Serial.begin(9600);      // Initialize Serial Port
}
 
void loop() {
  Serial.println("How old are you? ");        //Prompt User for input
  while (Serial.available()==0){}             // wait for user input
  age = Serial.parseInt();                    //Read user input and hold it in a variable
 
  // Print well formatted output
  Serial.print("You are ");                 
  Serial.print(age);
  Serial.println(" years old.");
}

I input 10, 15, and 36. Why there is 0 always followed by the integer that I input?

Probably because the Line ending setting that you have in the Serial monitor. Change it to no line ending

Or flush the old input before prompting for new input:

void loop() 
{
  // Flush the input buffer
  while (Serial.available())
    Serial.read();

  Serial.println("How old are you? ");        //Prompt User for input
  while (Serial.available()==0){}             // wait for user input

The advantage to doing this with a non-empty line ending is that .parseInt() won't have to wait for a timeout to detect the end of the number.

Thank you guys.
It works.

The critical part of your question was to identify if the zero value was in fact ‘before’ or ‘after’ your desired result…

That might have given you the hint about ‘extra values’ before or ‘after’ yiur inout…

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.