0

I have this function: int foo(char *string, int x, int y) Example input is: -.-..-...-. The program tokenises the string with the delimiter -. Then it counts the . in the tokens. The problem is the db variable does not change. After the counting the db has to be higher than x and lower than y. So -.-..-...- 2 3, the solution has to be 2.

    char *token;
    int length;
    int i;
    int db=0;
    int igaz=0;
    int j=1;

    token = strtok(string, "-");
    length = strlen(token);

    while(token != NULL)
    {
        length = strlen(token);

        for(i=0; i<length; i++);
        {
            if(token[i] == '.')
            //if(strcmp(token[i],'.')==0)
            {
                db++;
            }
        }

        if(db >= x && db <= y)
        {
            igaz++;
        }
        db=0;

        token = strtok(NULL, "-");
        j++;

    }
    return igaz;
7
  • 1
    What are x and y? Commented Nov 29, 2016 at 16:07
  • @Bela Karalyos : I've edited the question for spelling and grammar, but this is still not a minimal working example, see how to ask. Additionally, please add some example inputs & expected outputs. Commented Nov 29, 2016 at 16:10
  • Also if you are sure that string just has '-' and '.', why do you use for loop. db = strlen(token); right? Commented Nov 29, 2016 at 16:12
  • Is the whole thing part of foo()? If so, please fix. Commented Nov 29, 2016 at 16:13
  • 1
    There is a ; at the end of a for instruction: for(i=0; i<length; i++);! The following block is only executed when i is length... Commented Nov 29, 2016 at 16:27

1 Answer 1

1

There are multiple problems in your code. 1. For loop with semi colon.

for(i=0; i<length; i++);

This will just make the thread loop. But it will not execute the for loop body.

  1. strlen() will return string length excluding '\0' at the end. So your for loop should be from 0 to length as below.

for(i=0; i<=length; i++);

  1. For loop is unnecessary as string has only '-' and '.'

This will do that.

int foo(char *string, int x, int y)
{
    char *token;
    int igaz =0;
    int db   = 0;

    token = strtok(string, "-");

    while(token != NULL)
    {
       db = strlen(token);


       if(db >= x && db <= y)
       {
           igaz++;
       }

       token = strtok(NULL, "-");

    }
    return igaz;

}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! It works. With the next line: if(token[i] == '.'). What could be the problem?
@BélaKaralyos I updated the answer. Hope you find answer to your question.
God, i did not even notice that, it did not give me any error, or warning.. It is working now!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.