【发布时间】:2014-11-27 15:26:21
【问题描述】:
我有另一个关于 C 的问题 :( 我想用这个函数做的是检查令牌中的数字,如果没有,我把那个令牌放在一个字符串中,我稍后打印到文件中。我的函数看起来像这: const char *tarpas = " ";
{
const char *space = " ";
char *token, B[255];
int i, length, found = 0, x = 0;
token = strtok(A, space);
while(token != NULL){
for(i = 0; i < strlen(token); i++){
if((token[i] >= '0') && (token[i] <= '9')) found++; //If found a number
} //increase found
if(found == 0){ //if found = 0 means the word is clean
for(i = 0; i < strlen(token); i++){
B[x] = token[i];
x++;
}
B[x] = ' '; //adds a space after the token is in string
x++;
}
rado = 0;
token = strtok(NULL, tarpas); // get another token
}
print(B);
memset(B, 0, strlen(B)); //clear B string
}
我的数据文件:
ta5iip r345ytas suraitytas o rytoj gimimo rytas
asdasdasd
asdasd
我的结果文件:
asdasd \
rytoj gimimo rytas
(
应该是什么:
suraitytas o rytoj gimimo rytas
asdasdasd
asdasd
感谢您的任何意见!!!
【问题讨论】:
-
使用“isdigit”代替你的一对条件。使用 (memset B, 0, sizeof B) 而不是扫描额外的时间 - 并在使用前初始化 B。 “拉多”有什么作用?我建议将 strtok 调用放入单个 for 循环中,而不是间隔它们。您在不同的 strtok 调用中使用不同的分隔符指针的原因是什么?
-
@mpez0
isdigit(token[i])如果token[i] < 0而不是EOF,则为未定义行为。(token[i] >= '0') && (token[i] <= '9')没有这个问题。 -
@chux 我的手册页说 isdigit 是为任何无符号字符或 EOF 定义的。 “char”默认为有符号还是无符号取决于实现——我同意将 B 定义为无符号字符会更好。
标签: c string token strtok strlen