简体   繁体   中英

Convert char array to integers

I have a char array in the form of mm/dd/yy (as the user was asked to enter a date).

How do I split the array, and remove the / 's, and put mm , dd and yy into 3 different integers?

I would use sscanf to parse the string:

int m, d, y;    
sscanf("05/18/11", "%02d/%02d/%02d", &m, &d, &y);

This will parse the date into the three integer values.

In addition, to verify that the input data was formatted properly, you should also check that sscanf returned 3, indicating that all three values were properly parsed. See the following working example , which includes some basic error checking.

Look into strtok and atoi on the resulting tokens.

You could also use sscanf , but tokenizing provides more flexibility on the input format.

#include <stdlib.h>
#include <string.h>

int main()
{
    int month, day, year;
    char mystr[10] = "05/18/11";
    month = atoi(strtok(mystr, "/"));
    day = atoi(strtok(NULL, "/"));
    year = atoi(strtok(NULL, "/"));
    return 0;
}

strtok() is a function that takes on first call a string and a delimiter to split on. After the first call, it will continue to tokenize the same string if you pass NULL as the first argument. atoi converts a string to an integer.

If your input is really rigid, sscanf is good.

First, locate the nearest '/' :

int i;
char *d = date;
for(i = 0; date[i] != '/'; ++i);

Then apply a "substring":

strncpy(dd, date, i);

Repeat this process:

d = date + i + 1;
for(; date[i] != '/'; ++i);
strncpy(mm, d, i - (d - date));

Then simply go from the last '/' to the end of the string:

d = date + i + 1;
strncpy(yy, d, strlen(date) - i);

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