how to check if input is an integer in C++
So in this topic, we will first see what all data types are supported by C++. Then we see a code on how to check if the input is an integer in C++.
The datatypes supported by C++ is as follows:
Character: In primitive datatype, there is datatype defined to store the characters. We define keyword char and store the character. The char keyword takes 1 byte of memory space.
Boolean: The other type of primitive datatype is boolean it is used to store mainly the logic like 1 or 0 in the form of true or false. The keyword used is bool.
Floating Point: As we need decimal point values also for that the datatype is the Floating Point data type which is used for storing single-precision floating-point values or decimal values. The keyword used is float
Double Floating Point: To be precise about point values the larger precision values are stored in Double Floating Point. The keyword used is double.
Integer: For storing the integer values we use Integer Datatype which uses 4 bytes of memory space as per the computer specification. The keyword used to store integer value is int.
Check if input is an integer or not in C++
Now let’s write code on how to check if the input is an integer in C++:
#include <iostream> using namespace std; int main() { int i,count; string checkint; cout<<"Enter a number : "; cin>>checkint; for (i = 0; i < checkint.length(); i++) { if (isdigit(checkint[i]) == false) { count=1; break; } else count=0; } if(count==0) cout << "Integer"; else cout << "Not Integer"; }
Output:
Enter a number : 485k Not Integer
Enter a number : 782 Integer
Explanation:
In this code, we have taken the value of a number in a string called checkint after initialization we will calculate its length. For each character, we will check if it is a digit or not. If it is not a digit it will execute the if statement and the value of count will be 1. After the for loop gets over as per the value of count we will print it was an integer or other datatypes.
// were you having a stroke while writing this code?
// the readability is legit nightmare
// here let me rewrite it for new visitors
#include
using namespace std;
int main() {
int i,count;
string checkint;
cout<>checkint;
for (i = 0; i < checkint.length(); i++) {
if (isdigit(checkint[i]) == false) {
count=1;
break;
} else
count=0;
}
if(count==0)
cout << "Integer";
else
cout << "Not Integer";
}
// i had to use spaces to emulate tabs, sorry if you copied this and your IDE can't handle it
> Bitches about readability
> Comments code without any spaces/tabs at all, even as the “source code”, then blames
your IDE for not automatically including the imaginary spaces anon didn’t write in original
comment.