我得到一个字符串"小时"就像这个xx-yy,当这个字符串类似于我的时间时,xx是0和24之间的数字所以是yy而xxshoul比yy更小..我想写一个函数将这个字符串分成两个半xx和yy并且我想将它们转换为整数并检查它们..这是我到目前为止所写的: 当它到达strtok时,函数停止!任何想法为什么?谢谢。 更新:我收到此错误:没有可用于#34; strtok()" 。 输入示例小时= 23:17 ..
bool working_hrsIsValid(char* hours){
if (hours==NULL){
return false;
}
if(strlen(hours!=6){
return false;
}
char* ret=NULL;
ret=strchr(hours,'-');
if (ret==NULL){
return false;
}
char s[2] = "-";
char *token;
token = strtok(hours, s);
char* SRT_OPEN_HRS=token;
token = strtok(hours, s);
char* SRT_CLOSE_HRS=token;
int openH=stringtoNum(SRT_OPEN_HRS);
int closeH=stringtoNum(SRT_CLOSE_HRS);
if (openH<0 || openH>24 || closeH<0 || closeH>24){
return false;
}
if(closeH<openH){
return false;
}
return true;
}
答案 0 :(得分:2)
在这种情况下,函数sscanf
可能很方便。它避免了将字符串“手动”分成两部分,就像strtok
一样,它可能(有意)处理前导空格:
int main() {
int openH=0;
int closeH=0;
const char* hour = "0-23";
if (sscanf(hour, "%d-%d", &openH, &closeH) == 2) {
printf("opening hours from %02d to %02d\n", openH, closeH);
}
else {
printf("invalid format.\n");
}
return 0;
}
只是为了澄清“空格”的问题:格式"%d"
会跳过任何前导空格;格式"%d-"
会跳过前导空格,但在最后一位数字后面需要-
。以下代码添加了一些测试用例来说明这一点:
int working_hrsIsValid(const char* hours) {
int openH=0;
int closeH=0;
if ( (sscanf(hours, "%d-%d", &openH, &closeH) == 2)
&& openH >= 0 && openH < 24 && closeH >= 0 && closeH < 24) {
//printf("opening hours from %02d to %02d\n", openH, closeH);
return 1;
}
else {
//printf("invalid format.\n");
return 0;
}
}
void testOpenHoursFunction(const char *teststr[]) {
while (*teststr) {
printf("testing %s: %d\n", *teststr, working_hrsIsValid(*teststr));
teststr++;
}
}
int main() {
const char* validOnes[] = { " 0- 23", "3- 18", "04-05", NULL };
const char* invalidOnes[] = { "0 - 23", "-1- 23", "0-24", "0-", "-23", NULL };
testOpenHoursFunction(validOnes);
testOpenHoursFunction(invalidOnes);
return 0;
}
输出:
testing 0- 23: 1
testing 3- 18: 1
testing 04-05: 1
testing 0 - 23: 0
testing -1- 23: 0
testing 0-24: 0
testing 0-: 0
testing -23: 0