简体   繁体   English

Strtol()函数基本C

[英]Strtol() function basic c

When I am using the strtol() function, when I am trying convert: 当我使用strtol()函数时,当我尝试转换时:

2015-08-12

I would like it to fail conversion rather than converting only 2015 ? 我希望转换失败而不是仅转换2015吗?

int main(int argc, char *argv[])
{
     printf("Number of arguments: %d\n", argc);


  int i = 1;
  while (argc > i)
  {

  char *p;
  int num;

  errno = 0;
  long conv = strtol(argv[i], &p, 10);

// Check for errors: e.g., the string does not represent an integer
// or the integer is larger than int
  if (errno != 0 || *p != '\0' || conv > INT_MAX)
    {
      printf("this is word:%s\n ",p);
      //printf("chyba");
    }
  else
    {
    // No error
    num = conv;
    printf("this is number: %d\n", num);
  }

    i = i + 1;

  }
  return 0;
}

No, because strol() and the like convert the initial substring that matches. 否,因为strol()等会转换匹配的初始子字符串。 If you were to call it again on the rest of the string, though, you would need to strip out the dashes, or they would be interpreted as minus signs. 但是,如果要在字符串的其余部分再次调用它,则需要去除破折号,否则它们将被解释为减号。

The reason it appears that strtol() did not convert the text 2015 is because you want the terminating character to be '\\0' in this line 出现strtol()不能转换文本2015的原因是因为您希望该行的终止字符为'\\0'

if (errno != 0 || *p != '\0' || conv > INT_MAX)

But the text 2015 in 2015-08-26 is terminated by the '-' character. 2015-08-26的文字2015'-'字符终止。

So I recommend changing the line to 所以我建议将线更改为

if (errno != 0 || (*p != '\0' && *p != '-') || conv > INT_MAX)

There are other ways to tackle it: your code won't break the date into its parts. 还有其他解决方法:您的代码不会将日期分成几个部分。 You can do that by using strtok() but that wasn't your question. 您可以使用strtok()做到这一点,但这不是您的问题。

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

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