Thread: Accepting an input of multiple formats

  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    1

    Accepting an input of multiple formats

    I'm trying to create a code that accepts a date, however I want to give the user the ability to enter the date as dd/mm/yyyy or dd-mm-yyyy. My code is below, I tried to use %*C but its a cheat method as you can enter anything between the numbers in the date

    #include<stdio.h>
    #include<stdlib.h>
    #include<math.h>


    int main ()
    {
    int dayA, monthA, yearA;


    printf("First date in format DD/MM/YYYY or DD-MM-YYYY: ");
    scanf("%d%*c%d%*c%d", &monthA, &dayA, &yearA);
    Last edited by amukadam1; 04-23-2020 at 03:34 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,309
    A simple approach is to read the input as a string, e.g., using fgets. Then, attempt to parse this string using sscanf with "%d/%d/%d" as the format specifier, checking that the return value is 3. If it isn't, attempt to parse the string using sscanf with "%d-%d-%d" as the format specifier, checking for a return value of 3. If it isn't, the input is invalid. Otherwise, check that the values read are within the expected ranges.

    Alternatively, you can consider using regular expressions, if such a library is available to you. For example, you could read the input as a string using fgets, remove the trailing newline, then attempt to parse it using regex with the PCRE pattern:
    Code:
    ^(\d{2}/\d{2}/\d{4})|(\d{2}-\d{2}-\d{4})$
    You would still need to validate the ranges though.
    Last edited by laserlight; 04-23-2020 at 04:02 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Accepting input from keyboard
    By 7h3_0r4c1_3 in forum C Programming
    Replies: 1
    Last Post: 09-13-2011, 06:50 AM
  2. I need help with accepting multiple connections.
    By errigour in forum C Programming
    Replies: 2
    Last Post: 11-07-2010, 10:33 PM
  3. Accepting formatted input
    By fxtdr79 in forum C Programming
    Replies: 15
    Last Post: 06-28-2010, 01:25 PM
  4. Accepting Multiple Types of Input
    By Junior89 in forum C++ Programming
    Replies: 2
    Last Post: 03-07-2006, 11:25 PM
  5. accepting input while writing to screen
    By variable in forum C Programming
    Replies: 17
    Last Post: 02-06-2005, 10:14 PM

Tags for this Thread