Search code examples
cstringtokenstrtokstrlen

strings don't function properly


I have another problem concerning C :( what I want to do with this function is check for numbers in a token and if there are none I put that token in a string, which I later print to file. My function looks like this: 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
    }

My data file:

ta5iip r345ytas suraitytas o rytoj gimimo rytas
asdasdasd
asdasd

My result file:

asdasd \
  rytoj gimimo rytas
 (

What it should be:

suraitytas o rytoj gimimo rytas
asdasdasd
asdasd

Thank you for any kind of input!!!


Solution

  • You have to reset found in each iteration of the while loop.

    Also you have to exit loop

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

    if a digit was found in the string.

    This loop could be rewritten the following way

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

    It seems also that you read strings with function fgets that includes the new line character. You should remove this character from the string.

    ANd place statement

    memset(B, 0, strlen(B));          
    

    before the while loop or initially initialize array B to zeroes