Thread: Ask the user in C ?

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    2

    Ask the user in C ?

    hey guys..

    using C language,

    how can I ask the user to enter a positive integer

    in only these forms --> binary, octal, decimal, or hexadecimal

    then save it in a charachter array !

    after that I ask the user this question what's the base of this positive number..

    and from here I can tell if the form is octel or decimal or .. etc ! ..

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Try scanf().

    You can use %i in scanf() to read all octal, decimal, and hexadecimal depending upon the prefix the user gives the number. Otherwise, you can use %o, %d, and %x respectively.

    You can also use a method of reading the line as a string, and then using strtol() on the number, where you can tell the function what base to interpret the number.

    To save in a char array from an int, you could use sprintf() or snprintf().

  3. #3
    Registered User
    Join Date
    Jul 2007
    Posts
    2
    This is what I've done so far..

    Code:
    #include <stdio.h>
    
    int main()
    {
    	char posNumChar[30];
    
        printf("Please enter positive number: ");
    	
        fgets(posNumChar, 30, stdin);
    
        printf("You entered this positive number, %s", posNumChar);
    
        getchar();
    }
    now I want to do the second step.. which is asking the user for the base of the number he entered..

    I've been asked to avoid using scanf() to a character and using getchar() --- IN THIS STEP only !

    is there any other functions that work the same way as scanf and getchar !! ..

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    Another call to fgets() perhaps, storing the result in another string.
    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.

  5. #5
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    That or use fgets() again as Salem suggested, pull out what you want with sscanf() store the result in another variable.
    However in your case so far, that's clearly redundant.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Style Points
    By jason_m in forum C Programming
    Replies: 4
    Last Post: 05-28-2008, 06:15 AM
  2. Replies: 4
    Last Post: 04-03-2008, 09:07 PM
  3. Add/Delete Remotely a user
    By Scarvenger in forum Windows Programming
    Replies: 5
    Last Post: 03-24-2008, 08:36 AM
  4. Replies: 4
    Last Post: 04-21-2004, 04:18 PM
  5. ~ User Input script help~
    By indy in forum C Programming
    Replies: 4
    Last Post: 12-02-2003, 06:01 AM