简体   繁体   English

将char数组转换为整数

[英]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). 我有一个mm/dd/yy格式的char数组(因为要求用户输入日期)。

How do I split the array, and remove the / 's, and put mm , dd and yy into 3 different integers? 如何拆分数组,删除/ ,然后将mmddyy放入3个不同的整数?

I would use sscanf to parse the string: 我将使用sscanf解析字符串:

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. 另外,要验证输入数据的格式是否正确,还应该检查sscanf返回3,表明所有三个值均已正确解析。 See the following working example , which includes some basic error checking. 请参阅以下工作示例 ,其中包括一些基本的错误检查。

Look into strtok and atoi on the resulting tokens. 查看结果令牌上的strtokatoi

You could also use sscanf , but tokenizing provides more flexibility on the input format. 您也可以使用sscanf ,但是标记化为输入格式提供了更大的灵活性。

#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. strtok()是一个函数,该函数首先调用一个字符串和一个分隔符以进行分割。 After the first call, it will continue to tokenize the same string if you pass NULL as the first argument. 第一次调用后,如果您将NULL作为第一个参数传递,它将继续标记相同的字符串。 atoi converts a string to an integer. atoi将字符串转换为整数。

If your input is really rigid, sscanf is good. 如果您的输入确实很严格,则sscanf很好。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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