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?
Printable View
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.Quote:
This assumes the encoding scheme of ASCII,
and that '0' is the first of that sequence, and '9' is the last.Quote:
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.
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.
Cin is a global object that is used to read input from the console screen, from the user.
But you should probably get a book, because they explain all this in great detail.
There's a good thread that has many suggestions for books.