How to Check If the Input Is a Valid Integer Without Any Other Chars

How to check if the input is a valid integer without any other chars?

You could read a string, extract an integer from it and then make sure there's nothing left:

std::string line;
std::cin >> line;
std::istringstream s(line);
int x;
if (!(s >> x)) {
// Error, not a number
}
char c;
if (s >> c) {
// Error, there was something past the number
}

How to check if string input is a number?

Simply try converting it to an int and then bailing out if it doesn't work.

try:
val = int(userInput)
except ValueError:
print("That's not an int!")

See Handling Exceptions in the official tutorial.

Check if input is integer type in C

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:

int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key\n");

How can I check if a string represents an int, without using try/except?

If you're really just annoyed at using try/excepts all over the place, please just write a helper function:

def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False

>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False

It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

Check if string contains only digits

how about

let isnum = /^\d+$/.test(val);


Related Topics



Leave a reply



Submit