简体   繁体   中英

How do I make parts of a string into different integers in C?

char date[10];
scanf("%s",&date);

Let's say I enter a date in format YYYY-MM-DD; for example:

2019-06-17

How do I extract the parts with the numbers and make them into integers like int year, month, day; ?

Use strtol()

char p[] = "2020-11-03";
char *q;
int n1 = strtol(p, &q, 10);
int n2 = strtol(q + 1, &q, 10);
int n3 = strtol(q + 1, 0, 10);

Needs error checking, validation, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM