0

I'm writing an algorithm in C with netbeans to find asterisks in a string.

int main() {
    int M=0, i, j;
    scanf("%i",&M);
    int pos[M];
    char c[M];
    scanf("%s", c);

    i=0;
    j=1;

    while(c[i] != '\0'){
        if(c[i]=='*'){
            pos[j] = i;
            j++;
        }
        i++;
    }

    printf("Asterisks in positions: \n\n");

    for(j=1; j<=i; j++){
        printf("%i", pos[j]);
    }
    return 0;
}

But it doesn't work, it prints a lot of numbers even if M is a small number.

2
  • You did not ask a question. StackOverflow is a place to get questions answered. Commented Nov 30, 2010 at 4:24
  • What input are you giving your program? What output are you getting? What output do you expect? Commented Nov 30, 2010 at 4:24

3 Answers 3

2

The problem seems to be you never take into account the number of characters found. You print the whole vector, using i instead of j to iterate. It's j that holds the number of matches.

Also, try using strchr, from cstring :)

Get the first position, then search again from the next character until null is returned.

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

1 Comment

Or strcspn() which returns a count of the characters skipped.
1

The information regarding how many asterisks you found is stored in the counter j. This variable gets reset in the for loop:

for(j=1; j<=i; j++)

Furthermore, this for loop goes all the way up to i, which is the length of the your input string. Try reworking your loop as follows:

for(i=1; i<j; i++){    
    printf("%i", pos[i]);    
} 

Comments

0

After your while loop completes, j holds the total number of positions recorded, so you should be printing from pos[1] to pos[j]. Your current loop prints from pos[1] to pos[i]. Just invert the variables in your final loop:

for(i=1; i<=j; i++){
    printf("%i", pos[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.