Thread: using strchr

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    45

    using strchr

    trying to print the number of certain letter in a string but code gives general exception
    what to do, what to do...
    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main(void)
    {
    	char c,p[30]="breaka is one bad motha........er";
    	int pos,i=0,j,array[30];
    
    	printf("wich letter: ");
    	c = getchar();
    	scanf("%*[^\n]%*c");
    
    	while((pos=(strchr(p,c)-p))>=0){
    
    		array[i]=pos;
    		i++;
    	}
    	printf("number: %d\npositions: ");
    	for(j=0; j<i; j++)
    		printf("%d ",array[i]);
    
    return 0;
    }
    this message board is censuring the f word in code, what a laugh!!!
    Last edited by breaka; 08-12-2006 at 12:19 PM.

  2. #2
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    Most people on the board does not want to know what goes on between you and your mom at night.
    printf("number: %d\npositions: ");
    This call lacks arguments.

  3. #3
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    The function getchar returns an int.

    You keep searching the same string, so even if a letter is found, you never change your position in it and the same letter is found ove rand over (infinite loop). You should make a pointer to your array p, and say that pointer += pos; after you find a letter and add it to your array.

    Then you printf a number you don't specify an argument for.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Here's another laugh - read the rules.
    Closed.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing buffer with strchr
    By apsync in forum C Programming
    Replies: 3
    Last Post: 04-29-2007, 02:12 AM
  2. what is strchr func
    By vijlak in forum C Programming
    Replies: 2
    Last Post: 10-26-2006, 08:53 AM
  3. Using strchr() and moving the cursor up one row
    By Mavix in forum C Programming
    Replies: 7
    Last Post: 09-26-2006, 12:34 PM
  4. strchr()
    By paperbox005 in forum C Programming
    Replies: 8
    Last Post: 08-08-2004, 02:29 AM
  5. strchr
    By client in forum C Programming
    Replies: 2
    Last Post: 05-12-2002, 12:41 PM