Thread: Manipulating words in a string of characters

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    60

    Manipulating words in a string of characters

    Hey, new to C here
    I'm writing a program for school.
    I need to read in input from the keyboard (it could be 2 words or 1 page worth of input).
    Then I need to take each one of the words and put in into a char array and run some calculations on them (how many vowels are there, how many total letters, etc.)
    I have something like this:

    Code:
    char line[MAX_SIZE]; // array for whole input of the user
    char *tokenPtr         // a char pointer 
    char word[16];     //array for individual words
    
    printf("Enter String: ");  //prompt for string
    gets(line); 
    tokenPtr = strtok( line, " \t\n");  //begin tokenizing sentence
    
    while(tokenPtr !=NULL) {
      tokenPtr = strtok(NULL, " \t\n"); //get next token
    }//end while
    So for an input of : "hello world" , tokenPtr would first hold "hello" and then after the while loop it would hold "world".
    I would like to put the value that tokenPtr points to into a char array named word[] so i can calculate the number of vowels, the number of letters etc. Is there a way I can do that or has my approach been wrong so far?

    Ultimately i would like to have something like:

    Code:
    while(tokenPtr != NULL) {
      functionCalls();
      .
      .
      .
      tokenPtr = strtok(NULL, " \t\n");
    } //end while
    Is it possible to pass a char pointer such as tokenPtr into a char array and then run calculations on that array? If not, how can I approach this problem.

    Sorry about the long post oO

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by gp364481 View Post
    I would like to put the value that tokenPtr points to into a char array named word[] so i can calculate the number of vowels, the number of letters etc. Is there a way I can do that or has my approach been wrong so far?

    ...

    Is it possible to pass a char pointer such as tokenPtr into a char array and then run calculations on that array? If not, how can I approach this problem.
    You don't need to copy it.
    Aside from that, you also need to get rid of gets. See http://cpwiki.sourceforge.net/Gets.
    A pointer behaves the same as an array (plus when passing an array to a function, it becomes a pointer anyway), so you can just use the pointer returned by strtok directly.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    60
    Quote Originally Posted by Elysia View Post
    You don't need to copy it.
    Aside from that, you also need to get rid of gets. See http://cpwiki.sourceforge.net/Gets.
    A pointer behaves the same as an array (plus when passing an array to a function, it becomes a pointer anyway), so you can just use the pointer returned by strtok directly.

    You said it behaves the same as an array.
    So if there exists a pointer called char *tokenPtr; that points to the value "hello",
    is an expression such as tokenPtr[1]; valid? does it hold the value 'e' ?

    thanks alot for your replies

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by gp364481 View Post
    is an expression such as tokenPtr[1]; valid? does it hold the value 'e' ?
    Yes.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Sep 2008
    Posts
    60
    thank you I will try it when I get home tonight.

    why doesn't this work properly ? it just returns (n) spaces.

    Code:
    for(j=0; j < sizeof(tokenPtr); j++)
    	printf("&#37;c\n", &tokenPtr[j]);
    Last edited by gp364481; 09-09-2008 at 03:00 PM.

  6. #6
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by gp364481 View Post
    thank you I will try it when I get home tonight.

    why doesn't this work properly ? it just returns (n) spaces.

    Code:
    for(j=0; j < sizeof(tokenPtr); j++)
    	printf("&#37;c\n", &tokenPtr[j]);
    Hehe. What you're doing there is *almost* correct. In fact, you just need to get rid of the & (ampersand). The ampersand indicates that you want the address of the variable it belongs to. So you are in effect returning the address of tokenPtr[j], printf then tries to convert that into a character. I'm guessing that the addresses translate into some non-printable characters, which is why you're seeing spaces.
    Also, you don't really need that line. printf ("%s", tokenPtr); will work just fine as long as it is NULL terminated.

    QuantumPete
    Edit: Also fyi, sizeof (tokenPtr) will always return 4, because tokenPtr is a pointer and unless you're working on a 64bit system, your pointers are size 32bits = 4 bytes.
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You want strlen instead to get the length of the string.
    If you want, you can also do:
    printf("&#37;s\n", &tokenPtr[j]);
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Sep 2008
    Posts
    60
    Hey, thanks for the replies.
    I tried your suggestions and now after I input the string and press enter I get the message: "Segmentation Fault (core dumped)"

    Im including my code this time.
    Maybe you can spot the error. I suspect it has something to do with pointers, since they are new to me.




    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define MAX_SIZE 1000 /* max size of the char array*/

    Code:
    int main(void)
    {
    	int wordLength;
    	char line[MAX_SIZE];    /*array for the line of codeas a whole*/
    	char *tokenPtr;		/* create char pointer */
    	int sum, length, counter = 0; /*sum of all words */
    	float average;
    	int j, i=0;
    
    	printf("Enter String: ");	/*prompt for string */
    	gets(line);   /* use function gets from the string header to read input from keyboard */
    
    	tokenPtr = strtok( line, " \t\n");    /* begin tokenizing sentence */
    
    
    	while(tokenPtr != NULL) {
    		sum += findLength(tokenPtr);
    		counter++;
    		average = (float)sum / (float)counter; 
    		tokenPtr = strtok(NULL, " \t\n");    /*get next token */
    	}/*end while */
    
    
    	/*some sample calculations */
    
    	for(j=0; j < strlen(tokenPtr); j++)
    		printf("%s\n", tokenPtr);
    	for (i = 0; i < strlen(tokenPtr) ; i++ ){  
    		if ( tokenPtr[i] == 'a'  )  
    			printf("Found an a! \n");
    		else
    			printf("not found");
    	}
    
    
    	printOutput(sum, counter, average);
    	
    }
    int findLength(char *newWord)
    {
    	int length;
    	return length = strlen(newWord);
    }
    int printOutput(int s,int count,int ave)
    {
    	printf("the sum is %d\n", s);
    	printf("the number of words is %d\n", count);
    	printf("the average is %.2f\n", ave);
    }

    PS. I know that gets is evil and all, but this is the only way that i know for now. ;0
    thanks a bunch

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    1. sum is not initialized.
    2. You can't do strlen(NULL), or at any rate you don't want to do strlen(NULL), so your "sample calculations" will only lead to heartbreak.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    For the purposes in your code gets can be directly replaced with fgets(line, sizeof(line), stdin) and there will be no noticeable difference, except that if anyone ever enters a line longer than MAX_SIZE, the program will still work just as fine as before [ok, so if a word straddles the 1000 character point, it will be broken into two, but that is a much less serious problem than your program crashing under those same circumstances].
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  4. how to extract words from a string
    By panfilero in forum C Programming
    Replies: 7
    Last Post: 11-04-2005, 08:06 AM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM