Hi,
How can I set scanf such that it ignores hypens in the inputs and treats the whole as one number.
For example, if I enter the phone number 613-8933-5945 then I would like the input to be treated as '61389335945'.
Thanks
Hi,
How can I set scanf such that it ignores hypens in the inputs and treats the whole as one number.
For example, if I enter the phone number 613-8933-5945 then I would like the input to be treated as '61389335945'.
Thanks
You can't.
There are a few options for what you can do. You could read it as a string, and copy the relevant characters to a new string (using isdigit() to figure out which is a digit). You could read it character by character with getc(), storing only the relevant characters (this is a slight variant on the previous suggestion).
There are other options, but I figure the above would be pretty easy to implement.
Code:#include<stdio.h> main() { int a,b,c; scanf("%d-%d-%d",&a,&b,&c); printf("%d%d%d",a,b,c); }
*smacks forehead*
Cobmine murugaperumal's method with sprintf() (snprintf() is even better if it's available) and you probably have an ideal approach for the original request.
Sorry can't use strings.
I would also need to accept the numbers in the non hypened form.... so how would I also accomodate for that?
Thanks
I think that it's not possible with scanf. You can use simple regex with scanf but only on strings. Do you have to use scanf?
> Sorry can't use strings.
You mis-understood the requirement, or you're screwed.
The number you show as an example won't even fit in an integer on most common 32-bit machines.
If you have a phone number with leading zeros, then these will BE LOST when trying to read it as an integer.
> 613-8933-5945 then I would like the input to be treated as '61389335945'.
If you're expecting to be able to cope with both forms (with and without -), then you have to use strings.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.