Hi,
How can I control the input ?Code:scanf("%d",&x);
Thank youCode:if (x is a number) { //do this } else { //"I don't accept char!"; }
Hi,
How can I control the input ?Code:scanf("%d",&x);
Thank youCode:if (x is a number) { //do this } else { //"I don't accept char!"; }
Last edited by bchaib; 08-11-2008 at 03:22 PM.
use fgets/strtol pair with the full error checking procedure
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
this forum has a search feature... use it, write your own code - post it if you have some problemsbut how to use it
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
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.
But isdigit doesn't take a string, it takes a single char. You can of course use it once you have a string that MAY be a number - in whihc case you'd have to loop around checking each character. strtol() will do the looping for you, along with the process of converting it to an integer. Much easier, in my opinion.
--
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.
Yes I know and yes I did search for how 2 use fgets, but I didn't gbet anything.
My wone code?
And what I want to code is:Code:int x = 0; scanf("%d",&x); printf("Root of %d is %d",x,sqrt(x));
Code:int x = 0; scanf("%d",&x); if (x is a number) { printf("Root of %d is %d",x,sqrt(x)); } else { //wrong }
Greetings
Why are you doing this check? x will always be a number :P
If you want to get a charcater from the user youre probably best off using getchar()
You can then test if its a number using isdigit() from ctype.h
If you want to get a string then theres an example of how to use fgets in the FAQ
The value scanf/sscanf return is the number of items succesfully read. So, what you want is something like
Code:int nbItemsRead, x; nbItemsRead = scanf("%d", &x); // Here you should clear the input buffer if you use scanf instead of fgets + sscanf... // But I'm not telling you how... if (nbItemsRead == 0) { // The user didn't enter a number } else { // The user entered a number }
I hate real numbers.
You mean if I use fgets in stead of scanf ?Originally Posted by foxman
yes, just use fgets. you can find out how to use it in the FAQ