T. Daniels
T. Daniels

Reputation: 13

How do I separate integers from a string and manipulate them in C?

I am scanning for a date in the format mm-dd-yyyy and I need to take out three ints and use them for multiple things. How can I create three integers with mm dd and yyyy? Thanks!

Upvotes: 0

Views: 61

Answers (2)

lost_in_the_source
lost_in_the_source

Reputation: 11237

Use the sscanf call from <stdio.h>.

char line[80];
int m, d, y;

fgets(fgets(line, sizeof line, stdin);

sscanf(line, "%d-%d-%d", &m, &d, &y);

It is better to use fgets+sscanf instead of scanf directly, because scanf has the notorious \n issue and does not check buffer lengths.

Upvotes: 1

xing
xing

Reputation: 2508

Try this to use fgets for all input.
The do/while loops will continue until valid input is taken.
This only validates the month. Something should be added to verify day and year.
Check the return of sscanf to make sure the needed items have been successfully scanned.

#include <stdio.h>

int main(){
    char line[100] = "";
    int scanned = 0;
    int valid = 0;
    int mm = 0;
    int dd = 0;
    int yyyy = 0;

    int x;

    do {
        printf("\n\t\t\t1) Input date (mm/dd/yyyy) to find days passed");
        printf("\n\t\t\t2) Input passed days to find date in the year");
        printf("\n\n\t\t\tYour choice (1/2): ");
        if ( !( fgets ( line, sizeof line, stdin))) {
            fprintf ( stderr, "problem getting input found EOF\n");
            return 1;
        }
        if ( ( scanned = sscanf(line, "%d", &x)) != 1) {
            valid = 0;
        }
        else {
            if ( x == 1 || x == 2) {
                valid = 1;
            }
            else {
                valid = 0;
            }
        }
    } while ( !valid);

    if(x == 1) {
        do {
            printf ( "enter date mm-dd-yyyy\n");
            if ( !( fgets ( line, sizeof line, stdin))) {
                fprintf ( stderr, "problem getting input found EOF\n");
                return 1;
            }
            if ( ( scanned = sscanf ( line, "%d-%d-%d", &mm, &dd, &yyyy)) != 3) {
                valid = 0;
            }
            else {
                valid = 1;
                //validate the values for mm dd and yyyy
                if ( mm < 1 || mm > 12) {
                    printf ( "invalid month try again\n");
                    valid = 0;
                }
            }
        } while ( !valid);
    }
    return 0;
}

Upvotes: 0

Related Questions