字符串不能正常工作

时间:2014-11-27 15:26:21

标签: c string token strtok strlen

我有另外一个关于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

感谢您提供任何意见!!!

3 个答案:

答案 0 :(得分:1)

您必须在while循环的每次迭代中重置found

您还必须退出循环

    for(i = 0; i < strlen(token); i++){
        if((token[i] >= '0') && (token[i] <= '9')) found++; //If found a number
    }   

如果在字符串中找到了数字。

此循环可以通过以下方式重写

size_t n = strlen(token);
i = 0;
while ( i < n && ( token[i] < '0' || token[i] > '9' ) ++i;
found = i != n;

您还可以阅读包含新行字符的函数fgets的字符串。您应该从字符串中删除此字符。

和地方声明

memset(B, 0, strlen(B));          
在while循环之前

或者最初将数组B初始化为零

答案 1 :(得分:1)

你永远不会在循环内将found重置为零。

由于您在第一个令牌中找到了一个数字,这意味着您永远不会执行if(found == 0)代码。

反过来,这意味着当您打印B时,它仍未被初始化并且您正在打印一些随机数据。

您应该初始化B

char B[255] = {0};

并添加

found = 0;

作为循环的第一行。
或者,由于您没有在循环外使用found,因此将其移动到循环内。

while(token != NULL){
    int found = 0;
    /* ... */

答案 2 :(得分:1)

您忘记在while循环中初始化找到的变量。同样如@BLUEPIXY所述,B数组需要以'\ 0'结束。 所以代码如下:

{
const char *space = " ";
char *token, B[255];
int i, length, found = 0, x = 0;
token = strtok(A, space);
while(token != NULL){
    found = 0;
    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
}
B[x] = '\0';
print(B);
memset(B, 0, strlen(B));          //clear B string
}
相关问题