Thread: Quick Question Regarding Scanf() & Phone Numbers!

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    3

    Quick Question Regarding Scanf() & Phone Numbers!

    Hello everyone, this is my first post as i am just beginning to learn to program using C! my question is how would i go about asking for a phone number using scanf() with the exact format of (xxx)xxx-xxxx and then printing their answer to be in the format of xxx-xxx-xxxx?

    Example of my program:
    Please enter your phone number as (xxx)xxx-xxxx (exactly as shown, with no spaces): (123)456-7890 (This could be any number)

    Your phone number is 123-456-7890

    Thanks for the help!

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I wouldn't use scanf() at all, personally - but assuming that is what you HAVE to do:

    Option 1:
    char areacode[4], part1[4], part2[5]
    scanf("(%3s)%3s-%4s", areacode, part1, part2);

    Option 2:
    int areacode, part1, part2;
    scanf("(%3d)%3d-%4d", &areacode, &part1, &part2);

    Option 3:
    char phoneno[15];
    scanf("%s", phoneno);
    ... Verify that you got the correct format, and modify the string to new format.

    --
    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.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    3
    this is what i have so far. i want to output to look different then the input. (input being (xxx)xxx-xxxx and output being xxx-xxx-xxxx)
    Code:
    // Asks for the user's phone number then prints it //
    
    #include <stdio.h>
    
    int main( int argc, char **argv )
    {
    	int phoneNumber;
    	
    	printf( "Please enter your phne number as (xxx)xxx-xxxx (exactly as shown, with no spaces): " );
    	scanf( " %d", &phoneNumber );
    	
    	printf ( "Your phone number is %d\n", phoneNumber );
    	
    	return ( 0 );
    }

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    3
    OK i figured it out. thanks for the help matsp!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quick question about types...
    By Elysia in forum C++ Programming
    Replies: 32
    Last Post: 12-07-2008, 05:39 AM
  2. Question about random numbers
    By Kempelen in forum C Programming
    Replies: 2
    Last Post: 07-02-2008, 06:28 AM
  3. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  4. phone numbers using classes?
    By correlcj in forum C++ Programming
    Replies: 3
    Last Post: 11-09-2002, 06:31 PM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM