How can we make the serial input accept only integer?

Hello guys, I'm facing a problem in figuring out how to make my program accept only integer input and prompt the user to re enter a valid integer if not?

I wrote the following program for checking if the integer entered is a prime number or not. I need help about how can I make this program accept only integer input and prompt the user if an invalid input like a character or float number is entered.

int num1;
int num2;
int num3;
int i=2;
int checkerflag=0;
int printcounter=0;
void setup(){

Serial.begin(9600); //begins serial communication

}

void loop()
{

if(printcounter==0)
{
Serial.println("Enter the integer to check if prime or not");
printcounter=1;
}
while(Serial.available()>0)
{
num1=Serial.parseInt();

num2=sqrt(num1)+2;
checker();



}
}
 
void checker()
{
while(i<num2)
{ 
num3=num1%i;
    
if(num3==0){checkerflag=1; break;}
i=i+1;
}
Serial.print("Number ");
Serial.print(num1);
if(checkerflag==0)
{ 
  Serial.println(" is a prime.");
}
else
{
  Serial.println(" is not a prime");
}
checkerflag=0;
i=2;

}

Thank you in advance :slight_smile:

What's the problem you're facing?

Please remember to use code tags when posting code

I want to make my program only accept integer input.

Also if anything else other than an integer is entered, l want to display an error message.

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

And there is a simple user-input example in Planning and Implementing a Program

...R

Also if anything else other than an integer is entered, l want to display an error message.

So, what IS the problem? You read a char7acter, and if it is not what you expe5t, you decide what to do with that chara7te8r.

Ignore just that character? Ignore all input up to that point? Piss and moan?