Thread: Need help with functions

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    13

    Question Need help with functions

    I am having trouble with my homework assignment and can't seem to figure out what I am doing wrong. The assignment is to build a program that gives a user 4 options. They are:
    1- Enter 2 words. The program will then determine if they are identical.
    2- Enter a sentence. The program will then count the words and display the sentence back along with word count.
    3- Enter 2 strings. The program will print each separately and then create a new string displaying them combined with a space between them.
    4 - End the program.

    Each option (minus 4) has to be in it's own function with the input being passed via pointers. I was able to get the loop for the menu, lay out cases for the options, and finish options 1 & 4 with no problem. Options 2 & 3 are the issue. With each I have been able to successfully code what I need to happen in their own separate programs just using the main function. But when I try to copy it into my homework file I can't figure out what the function needs to return to main. Because of this I am pretty sure my prototypes, along with the variables passed, are wrong.
    Also the program doesn't seem to stop to allow user input in some spots. As you will see in the full code, for case 2 I have
    Code:
                    printf( "Please enter a sentence: " );   
                    gets( &text);
    
    
                    countWords(text, counter);
                    printf( "\nThe total number of words is %d\n", counter );
    But when I run the program it doesn't stop to allow input, just says "The total number of words is 0" and brings up the menu again.

    Here is the full code:
    Code:
    /* Eric Zaytoun
    4-12-2012
    CIT-145
    Program 4
    This program will give the user 4 options. In the 1st, the user will enter two words.
    The program will determine if the words are identical and tell the user if they are or if they are not.
    Option 2 will prompt the user to enter a sentence. The program will count the number of words
    and display the sentence and word count to the user. Option 3 will allow the user to enter 2 strings.
    The program will display each individual string, and display a new string combining them.
    Option 4 will close the program.
    
    
    */
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    
    //Prototype functions
    int compareStrings(char*, char*);    //Option 1 - Compare strings
    void countWords(char*, int);
    
    
    // Function main executes the program
    int main( void )
    {
        int choice = 0;    //Variable to hold users selection
        char first[400];
        char second[400];
        char result;
    
    
        char text[400];
        int counter = 0;
    
    
        while( choice !=4 ){    //loop for selection
            
            printf("Please enter 1, 2, 3, or 4 for the option you would like to select: \n"
            "1- Compare two words to see if they are identical. \n2- Count the number of words in a sentence. \n"
            "3- Enter two strings and have them combined. \n4- End the program.\n");
    
    
            scanf("%d", &choice);
    
    
            switch( choice ) {    //sends the user choice to each function
                case 1:
                    //retieve words from user
                    printf("Enter first string: ");
                    scanf("%s", &first);
     
                    printf("Enter second string: ");
                    scanf("%s", &second);
     
                    //send to function compareStrings
                    result = compareStrings(first, second);
     
                    //display results
                    if ( result == 0 )
                        printf("The words are identical.\n\n");
                    else
                        printf("The words are not identical.\n\n");
                    break;
                case 2:
                    //funtion for sentence count
                    printf( "Please enter a sentence: " );
       
                    gets( &text);
    
    
                    countWords(text, counter);
                    printf( "\nThe total number of words is %d\n", counter );
                    break;
                case 3:
                    //funtion for combining strings
                    break;
                case 4:
                    //ends program
                    break;
                default:
                    printf("Please make a valid selection.\n\n");
                    break;
            }//End switch
        }//End while loop
    }// Ends function main
    
    
    //Function compareStrings compares strings for option 1
    int compareStrings(char *first, char *second)
    {
       while(*first==*second)
       {
          if ( *first == '\0' || *second == '\0' )
             break;
     
          first++;
          second++;
       }
       if( *first == '\0' && *second == '\0' )
          return 0;
       else
          return -1;
    }//End function compareStrings
    
    
    void countWords(text, counter)
    {
        char *pointer;
        counter = 0;
         
      
        pointer = strtok( &text, " \n" );
          
        while ( pointer ) { 
            ++counter;
            pointer = strtok( NULL, " \n" );
       }
          
    }
    Like I said, when I code the countWords function in a main function it works, i'm just not sure how to convert it to a separate function.
    And sorry if it's a little sloppy tab wise, I'm been editing it so much trying to solve this that I have kinda slacked on keeping them straight. Any help would be much appreciated.

  2. #2
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    After stepping away for a few hours and coming back with fresh eyes, I was able to fix my issues with getting the input and the entire Option 2. All I have left is Option 3.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    120
    When calling function like this
    Code:
    countWords(text, counter);
    you are passing parameter counter by value - the function will be unable to change it.
    There are 2 ways to solve this problem:

    1. Pass pointer to variable
    Code:
    countWords(text, &counter);
    and make necessary modifications in function body using * operator.

    2. Redefine function to return a value.
    Code:
    int countWords(char*);

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Also never use gets for any reason. Use fgets() instead.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  5. #5
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    Thanks everyone. I have run into one last problem. When I get to the function that combines strings with an added space, I keep hitting a breaking point and am not sure why. (My class has done a horrible job explaining how to debug when it's not a syntax or mathematical error)

    This is my prototype
    Code:
    char combineString(char string1, char string2);    //Option 3- combine strings
    In main I have this:
    Code:
        char string1[20];
        char string2[20];
        char stringCombined[80];
    
                    printf("Please enter first string: ");
                    scanf(" %[^\n]", string1);
    
    
                    printf("Please enter second string: ");
                    scanf(" %[^\n]", string2);
    
    
                    printf("\nFirst string is: %s\n", string1);
                    printf("Second string is: %s\n", string2);
    
    
                    printf("Combined string is: %s\n\n", combineString(string1,string2), stringCombined);
    And here is the function combineString
    Code:
    //Function combineString for option 3
    char combineString(char string1, char string2)
    {
        char stringCombined[42];
    
    
        strcat(stringCombined, string1);
        strcat(stringCombined, " ");
        strcat(stringCombined, string2);
    
    
        return stringCombined;
    
    
    }//End function combineString
    The breakpoint is at the first strcat line in the function. This is the error messege I recieve: "Unhandled exception at 0x6224f693 in test.exe: 0xC0000005: Access violation reading location 0x0000000c."

  6. #6
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    You need to be returning a char* not char, change your prototype....Also, look at this code closely and see what you have wrong
    printf("Combined string is: %s\n\n", combineString(string1,string2), stringCombined);

  7. #7
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    ", stringCombined" shouldn't be there because the %s will refer to combineString? ....I'm guessing I'm wrong cuz I still am getting the error, but I have no idea.

  8. #8
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Yes, remove stringCombined and then try to recompile it.

  9. #9
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    After I enter strings when prompted it displays each then the error pops up showing the break point at the same line. Any ideas on what else it could be?.... When testing I'm only entering 1 character strings so I don't think it has to do with the array sizes.

  10. #10
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Post your entire code

  11. #11
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    Code:
    /* Eric 
    4-12-2012
    CIT-145
    Program 4
    This program will give the user 4 options. In the 1st, the user will enter two words.
    The program will determine if the words are identical and tell the user if they are or if they are not.
    Option 2 will prompt the user to enter a sentence. The program will count the number of words
    and display the sentence and word count to the user. Option 3 will allow the user to enter 2 strings.
    The program will display each individual string, and display a new string combining them.
    Option 4 will close the program.
    
    
    */
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    
    //Prototype functions
    int compareStrings(char*, char*);	//Option 1 - Compare strings
    int countWords(char text);	//Option 2- count words
    char* combineString(char string1, char string2);	//Option 3- combine strings
    
    
    // Function main executes the program
    int main( void )
    {
    	int choice = 0;	//Variable to hold users selection
        char first[20];
    	char second[20];
    	char result;
    
    
    	char text[20];
    	int counter = 0;
    
    
    	char string1[20];
    	char string2[20];
    	
    	while( choice !=4 ){	//loop for selection
    		
    		printf("Please enter 1, 2, 3, or 4 for the option you would like to select: \n"
    		"1- Compare two words to see if they are identical. \n2- Count the number of words in a sentence. \n"
    		"3- Enter two strings and have them combined. \n4- End the program.\n");
    
    
    		scanf("%d", &choice);
    
    
    		switch( choice ) {	//sends the user choice to each function
    			case 1:
    				//retieve words from user
    				printf("Enter first string: ");
    				scanf("%s", &first);
     
    				printf("Enter second string: ");
    				scanf("%s", &second);
     
    				//send to function compareStrings
    				result = compareStrings(first, second);
     
    				//display results
    				if ( result == 0 )
    					printf("The words are identical.\n\n");
    				else
    					printf("The words are not identical.\n\n");
    				break;
    			case 2:
    				//Get sentence
    				printf( "Please enter a sentence: " );
       				scanf(" %[^\n]", text);
    				
    				//Display sentence
    				printf(" \nYour sentence was: %s\n", text);
    
    
    				//Count & display number of words				
    				printf( "The total number of words is %d\n\n", countWords(text), counter );
    				break;
    			case 3:
    		
    				printf("Please enter first string: ");
    				scanf(" %[^\n]", string1);
    
    
    				printf("Please enter second string: ");
    				scanf(" %[^\n]", string2);
    
    
    				printf("\nFirst string is: %s\n", string1);
    				printf("Second string is: %s\n", string2);
    
    
    				printf("Combined string is: %s\n\n", combineString(string1,string2));
    
    
    				break;
    			case 4:
    				//ends program
    				break;
    			default:
    				printf("Please make a valid selection.\n\n");
    				break;
    		}//End switch
    	}//End while loop
    }// Ends function main
    
    
    //Function compareStrings compares strings for option 1
    int compareStrings(char *first, char *second)
    {
       while(*first==*second) //compare characters of each string
       {
          if ( *first == '\0' || *second == '\0' )
             break;
     
          first++;
          second++;
       }
       if( *first == '\0' && *second == '\0' )
          return 0;
       else
          return -1;
    }//End function compareStrings
    
    
    //Function countWords counts the words for Option 2
    int countWords(char text[])
    {
    	int counter = 1;	//initialize counter
    	int i = 0;	//temporary array counter
         
    	while ( text[i] != '\0' ) { //loop to check for spaces
    		if( isspace(text[i]) ){
    			++counter;
    		}
    		i++;
    	}
    
    
    	return counter;
          
    }//End function countWords
    
    
    //Function combineString for option 3
    char* combineString(char string1, char string2)
    {
    	char stringCombined[42];
    
    
    	strcat(stringCombined, string1);
    	strcat(stringCombined, " ");
    	strcat(stringCombined, string2);
    
    
    	return stringCombined;
    
    
    }//End function combineString

  12. #12
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    There are many syntax errors that you need to fix, Your telling me that this compiled fine with no errors??

  13. #13
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    yeah, 0 errors. I'm using Visual C++ 2008 Express if that matters. There are some warnings like:
    warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    but scanf is what is in the book and teachers lecture notes so thats why I haven't changed them.

  14. #14
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    I got a ton of errors, Ok so tell me again what happens exactly when you run it, Right now I have it and its working perfectly. I do know that in your combine string function you should be using malloc and returning that pointer back to main.

  15. #15
    Registered User
    Join Date
    Apr 2012
    Posts
    13
    The menu opens up. I type '3' - Enter. It asks for the first string. I type 'the'- Enter. Asks for second string. I type 'cat' - Enter. It prints:
    First string is: the
    Second string is: cat

    Then a message box opens in VCExpress saying "Unhandled exception at 0x61fef693 in test.exe: 0xC0000005: Access violation reading location 0x00000078." with 2 options Break & Continue. When I choose continue it just pops up again. When I choose break it closes and goes back to the code, with an arrow next to line 136, strcat(stringCombined, string1);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. WinAPI functions - similar functions as part of VS C++
    By jlewand in forum Windows Programming
    Replies: 2
    Last Post: 02-02-2012, 08:54 AM
  2. Creating Functions & passing information to other functions
    By RyanLeonard in forum C Programming
    Replies: 4
    Last Post: 10-28-2010, 12:17 PM
  3. Replies: 7
    Last Post: 04-19-2006, 11:17 AM
  4. Replies: 6
    Last Post: 05-06-2003, 03:08 PM
  5. Replies: 1
    Last Post: 01-20-2002, 11:50 AM