Is it possible to read negative numbers (-93, -9) and numbers that are longer than one digit (269) via the getchar function?
I've searched the web but to no avail.
If it's possible how can it be done?
Thank you
Is it possible to read negative numbers (-93, -9) and numbers that are longer than one digit (269) via the getchar function?
I've searched the web but to no avail.
If it's possible how can it be done?
Thank you
The function getchar() [which I think is a macro - but we'll ignore that for the second] returns a single character as an integer. So getchar() will return 65 for the letter A, 97 for the letter a. If you get negative numbers, it's most likely because it's -1, which indicates that your application hit end of file (most likely if you are redirecting input from a file).
If you are after reading NUMBERS, the first function that comes to mine is scanf(), but it's a bit "faulty", in that it's "easily confused by clumsy users", e.g. if you input 32A, if the next scanf() is then trying to read another number, it will get "stuck".
Ideally, use fgets() and sscanf() or strtol().
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
The thing is the professor required us to read negative numbers and numbers that are more than one digit via getchar()... so is there any way whatsoever. Pretty much the user has to enter a number (pos. neg. or longer than one digit) and we need to process it.
Can it be done in any way?
pointers perhaps (even though I cannot see how that would help...)
Thanks.
You could always use getchar to get characters, then put them in a string. Then use strtol(), but its definitely overkill.
Teacher: "You connect with Internet Explorer, but what is your browser? You know, Yahoo, Webcrawler...?" It's great to see the educational system moving in the right direction
Like happy reaper says, you can do that. You don't NECESSARILY have to do it using strtol() either, if you don't want to - just imagine how you do things if you where to take a digit at a time and make it into a large number by yourself (think of it as one of these TV show games where you only see one digit first, then get a second, a third, etc, etc).
Note that negative numbers are easiest to deal with if you notice that there is a "minus" character and just set a variable to say "the number is negative", then later on just turn the sign. Something like this:--Code:int neg = 0; ... ch = getchar(); if (ch == '-') neg = 1; .... // Number input finished. if (neg) number = -number; ...
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.