简体   繁体   English

如何将 char 数组标记为 C 中的不同 int?

[英]How do I tokenize a char array to different int in C?

I'm not familiar with C and I'm getting frustrated.我对C不熟悉,我感到很沮丧。 I need to create 3 int variables from the char array token.我需要从char数组令牌创建 3 个int变量。 This is supposed to be a date mm/dd/yyyy.这应该是一个日期 mm/dd/yyyy。 My 3 int variables would be:我的 3 个int变量是:

int monthNum; 
int dayNum;  
int yearNum;
void handlePrint() { 
  char token[MAX_COMMAND_TOKEN_LENGTH]; // Placeholder for the first argument
  int weekDays = 7;
  int numDays = 31;

  if (getCommandWord(token, MAX_COMMAND_TOKEN_LENGTH) != '\n') {
    printf("Too many arguments for print command! It must be in the form of print MM/DD/YYYY.\n");
    while (getCommandWord(token, MAX_COMMAND_TOKEN_LENGTH) != '\n');
    return;
  }
  printf("printing the weeks of month %s\n\n", token);
}

I tried to tokenize the token by doing the following:我尝试通过执行以下操作来标记令牌:

char* endPoint = "/";
long int monthN = strtol (token, &endPoint, 10);

which gets the first variable, how can I create the two other variables?它得到第一个变量,我怎样才能创建另外两个变量?

I would really appreciate your help!我将衷心感谢您的帮助!

Continuing from my comment above, given you are separating a date, if token is returned as a string from getCommandWord(token, MAX_COMMAND_TOKEN_LENGTH) != '\n') , then simply passing token to sscanf() is an easy way to separate the month, day and year values.继续我上面的评论,假设您要分隔日期,如果token作为字符串从getCommandWord(token, MAX_COMMAND_TOKEN_LENGTH) != '\n')返回,那么只需将token传递给sscanf()是一种简单的方法来分隔月、日和年的值。 You could simply do:你可以简单地做:

    if (sscanf (token, "%2d/%2d/%4d", &monthNum, &dayNum, &yearNum) != 3) { 
        fputs ("error: invalid token format.\n", stderr);
        return 1;
    }

That will separate the monthNum , dayNum and yearNum into integer values, but you will still need to validate that monthNum is 1 - 12 , dayNum is 1 - 31 (at minimum) and then optionally handle yearNum as either a 1-digit, 2-digit or 4-digit value.这会将monthNumdayNumyearNum分成 integer 值,但您仍然需要验证monthNum1 - 12dayNum1 - 31 (至少),然后可以选择yearNum处理为 1 位、2-位或 4 位数值。 This can largely be handled however you like;这在很大程度上可以随心所欲地处理; eg if the year is less than 21 assume the present century and add 2000 , if the year is greater than 21 an less than 100 add 1900 , etc. This is completely up to you.例如,如果年份小于21假设当前世纪并添加2000 ,如果年份大于21且小于100则添加1900等。这完全取决于您。

A quick example that implements the logic above, after prompting the user to enter a date could be done similar to the following.一个实现上述逻辑的快速示例,在提示用户输入日期之后,可以类似于以下方式完成。 fgets() is used for input as getCommandWord() is not given in your code: fgets()用于输入,因为您的代码中没有给出getCommandWord()

#include <stdio.h>

#define MAXC 256        /* if you need a constant, #define one (or more) */

int main (void) {
    
    char input[MAXC];
    int m, d, y;
    
    fputs ("enter date (mm/dd/yyyy): ", stdout);                /* prompt */
    if (fgets (input, MAXC, stdin) == NULL) {                   /* read/validate input */
        puts ("(user canceled input)");
        return 0;
    }
    if (sscanf (input, "%2d/%2d/%4d", &m, &d, &y) != 3) {       /* separate int m, d, y */
        fputs ("error: invalid input format.\n", stderr);
        return 1;
    }
    /* validation of m, d, y values */
    if (m < 1 || 12 < m) {                                      /* check month 1-12 */
        fputs ("error: invalid month value.\n", stdout);
        return 1;
    }
    if (d < 1 || 31 < d) {                                      /* check day 1-31 */
        fputs ("error: invalid date value.\n", stdout);
        return 1;
    }
    /* adjust 2-digit day, 0-21 year 2000, 22-99 year 1900  */
    if (y <= 21)
        y += 2000;
    else if (y < 100)
        y += 1900;
    
    printf ("month : %d\nday   : %d\nyear  : %d\n", m, d, y);
}

This is just a quick example, you can, and should adjust the year handling and add any additional validations to fit your requirements.这只是一个简单的示例,您可以并且应该调整年份处理并添加任何其他验证以满足您的要求。

Example Use/Output示例使用/输出

Full number of digits完整位数

$ ./bin/split_date
enter date (mm/dd/yyyy): 12/21/1967
month : 12
day   : 21
year  : 1967

Single digit month/day, 2-digit year greater than 21:一位数月/日,大于 21 的两位数年:

$ ./bin/split_date
enter date (mm/dd/yyyy): 1/2/67
month : 1
day   : 2
year  : 1967

2-digit year less than or equal to 21:小于或等于 21 的 2 位数年份:

$ ./bin/split_date
enter date (mm/dd/yyyy): 2/11/21
month : 2
day   : 11
year  : 2021

Invalid month:无效月份:

$ ./bin/split_date
enter date (mm/dd/yyyy): 13/11/21
error: invalid month value.

Look things over and let me know if you have further questions.如果您还有其他问题,请仔细查看并告诉我。

Thank you so much, that helped me a lot, If I need to do the same?非常感谢,这对我帮助很大,如果我需要这样做? but with 2 tokens in the same line separated by a space (mm/dd/yyyy mm/dd/yyyy) How could I do it?但是在同一行中有 2 个标记,由空格分隔 (mm/dd/yyyy mm/dd/yyyy) 我该怎么做?

char token1[MAX_COMMAND_TOKEN_LENGTH]; //1st arg (from date) 
char token2[MAX_COMMAND_TOKEN_LENGTH]; //2nd arg (to date) 

int month1, month2; 
int day1, day2; 
int year1, year2; 

So it's the same situation, but now I need to print 6 different int variables because I have two dates.所以情况相同,但现在我需要打印 6 个不同的 int 变量,因为我有两个日期。

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

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