Thread: Allow them to enter numbers only

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    7

    Allow them to enter numbers only

    Please help me
    I want users to enter numbers only

    Code:
    #include <stdio.h>
    
    int main () {
    	float	num;
    
    	printf	("Please Enter Number You want Square of: ");
    	scanf	("%f", &num);	
    	>>>Something here it tells users to enter numbers only if they enter alphabets then it should not work<<<<
    	printf  ("%0.2f squared is equal to %0.2f\n", num, num * num);
            
    	return 0;
    }

  2. #2
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    You do want to read the user input as text, check if it is numeric, and then do the conversion.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    7
    it does work
    lets say if it ask user to enter number, and if user enters K
    than my program should tell them to enter numbers only

  4. #4
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    I would still read the input as text, and do checks and conversion myself.

    But you might want to search the documentation for scanf to see, if there's some return values specified for it.

  5. #5
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    you can check the return value of scanf

    Code:
    double a;
    if (scanf("%lf", &a) != 1) {
    //the user didn't enter a number
    } else {
    ...
    }
    But it will work if the user enters a number followed by something else. Eg, "10.5 asdf"

    Depends on what you are trying to do, that can be good or bad.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Frustated with mess table printing
    By benedicttobias in forum C Programming
    Replies: 6
    Last Post: 04-16-2009, 05:50 PM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. endless loop for scanf - plz help
    By owi_just in forum C Programming
    Replies: 18
    Last Post: 03-20-2005, 01:41 PM
  4. How would I only enter numbers and not characters
    By chrismax2 in forum C++ Programming
    Replies: 5
    Last Post: 04-21-2004, 03:19 PM
  5. terminate 0 - PLEASE HELP
    By Unregistered in forum C Programming
    Replies: 11
    Last Post: 11-21-2001, 07:30 AM