How can you check if for example the x[30] char has numbers in it, without using any specific function if possible? And the same with ints, how do you check if it's a number?
How can you check if for example the x[30] char has numbers in it, without using any specific function if possible? And the same with ints, how do you check if it's a number?
Best way of doing it is using std::isdigit. It takes a single character, so if you want to check the entire string, you'll have to loop through it. It's the recommended way for portability.
And integers are integers, not strings. In fact, strings are characters which are integers, so it's impossible to separate those.
Is there a specific situation you're thinking of?
This assumes the encoding scheme of ASCII, which I think is an assumption that is safe to make.Code:bool has_numbers = false; for (int i = 0; i < 30; ++i) { if (x[i] >= '0' && x[i] <= '9') { has_numbers = true; break; } }
But of course, std::isdigit is a better solution, if you don't mind using the standard library. (why not?)
It doesn't. It merely assumes that the digits are sequential in the encoding, which is a requirement of the standard. And it assumes that digits are represented by a single byte, which is not a requirement AFAIK, but you'll be hard-pressed to find an implementation where it is not the case.This assumes the encoding scheme of ASCII,
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
and that '0' is the first of that sequence, and '9' is the last.digits are sequential in the encoding
2.2/3 says:
"In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous."
where above list is:
0 1 2 3 4 5 6 7 8 9
So yeah, that too.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
if you mean checking for user input, I think the convention is to try to read into an integer, and then check for the fail flag of the stream.
Code:int should_be_a_number; cin >> should_be_a_number; if (cin.fail()) { ... // the user didn't input a number }
google is your friend
http://www.google.ca/search?hl=en&q=...G=Search&meta=
We're not your personal teaching assistants.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law