【问题标题】:Problem with if statements, containing token from strtok in Cif 语句的问题,包含来自 C 中 strtok 的标记
【发布时间】:2021-12-05 08:34:05
【问题描述】:

这是任务: 1)07/21/2003 2)2003 年 7 月 21 日

编写一个程序,以第一种格式读取日期并以第二种格式打印。

我应该使用字符串方法,尤其是 strtok

这是我的代码:

#include <stdio.h>
#include <string.h>

int main()
{
    char date[20];
    char month[20];
    char day[20];
    char year[20];
    char *token;
    char sep[1] = "/";

    printf("Enter the date (MM/DD/YYYY): ");
    gets(date);

    token = strtok(date, sep);

    if (token == "01")
    {
        strcpy(month, "Januray");
    }

    else if (token == "02")
    {
        strcpy(month, "February");
    }

    //continuing in this way
   
    }

    else if (token == "11")
    {
        strcpy(month, "November");
    }

    else
    {
        strcpy(month, "December");
    }

    token = strtok(NULL, sep);
    strcpy(day, token);

    token = strtok(NULL, sep);
    strcpy(year, token);

    printf("%s %s, %s", month, day, year);
}

问题是月份部分总是给出十二月,这意味着如果语句不起作用。

【问题讨论】:

  • 该令牌的价值究竟是什么
  • 在 C 中(请标记)我认为您不能将字符串值与 == 进行比较
  • “我应该使用字符串方法”。其中之一是strcmp,检查它的作用。
  • @HansKesting 和字符串一样,我用strcmp方法测试它返回值0
  • 到底检查了什么?在哪里? “我将双方程改为单方程”这不是你应该做的。再次检查strcmp 的作用。

标签: c if-statement strtok


【解决方案1】:

这样写

if (token == "01")    

不做你认为它做的事,token 指向字符串的开头(日期),所以你是在比较两个地址,而不是比较实际的字符串内容使用 strcmp()。

if (strcmp(token,"01") == 0)

但是上面的方法有点容易出错,如果用户输入“1”呢?所以更好的方法是将其转换为整数:

char* tokenend = NULL;
int mon = strtol(token, &tokenend, 10);

那么您可以在 switch 中使用mon,这会使代码不那么冗长。

switch(mon) {
  case 1:
    strcpy(month,"January");
    break;
    ...
  default:
    fprintf(stderr, "Invalid month entered %s", token);
    break;
}    

还要注意strtok 改变了date 的内容,所以原来的日期已经不复存在了。如果要保留原始字符串,则需要单独存储。

一般来说,从键盘读取字符串时应使用fgets 而不是gets,因为gets 不限制它可以读取的字符数

if (fgets(date, sizeof(date), stdin) != NULL)
{
  // and remove the \n
  char* p = strchr(date,'\n');
  if (p != NULL) *p  = '\0';
}

【讨论】:

  • 如果使用数组而不是大的switch 语句,则代码不会那么冗长:const char* months = {"January", "February", ...};
  • @n.1.8e9-where's-my-sharem。你的意思可能是char* months[],但是是的,关键是评估月份数字会减少出错的可能性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 2018-03-23
相关资源
最近更新 更多