When I am using the strtol()
function, when I am trying convert:
2015-08-12
I would like it to fail conversion rather than converting only 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. 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
if (errno != 0 || *p != '\0' || conv > INT_MAX)
But the text 2015
in 2015-08-26
is terminated by the '-'
character.
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.
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.