Thread: switch case statement ignoring input from another function

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    3

    switch case statement ignoring input from another function

    Hello, I have a question regarding the following code. I have two functions in it, one called SetupReverse() and the other printReverse(char str[])

    SetupReverse allocates memory for an user to enter a sentence. and printReverse takes that sentence and prints it in reverse. i.e. "C programming language is cool" becomes "cool is language programming C"

    It was working until I decided to include a switch case statement in main to make it more interactive and now it doesn't even prompt me to enter the sentence, it skips it completely. Why?

    Code:
    #include <stdio.h>#include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    
    
    
    /* Function that prints sentence in reverse
     * 'Hello to the world' becomes
     * 'world the to Hello'
     * */
    void dogcat();
    /*Sets up the text that will be reversed*/
    void SetupReverse();
    /*Reverses the text that was typed in SetupReverse() function*/
    void printReverse(char str[]);
    
    
    /*Start 
     * of 
     * Main
     * */
    
    
    int main(int argc, char **argv)
    {
    	int option;
    	printf("Please Select one of the following options: \n");
    	printf("1	Cats and Dogs\n");
    	printf("2	Reverse Text\n\n");
    	scanf("%d",&option);
    	
    	while(1){
    		
    		switch(option)
    		{	
    			case 1:
    			dogcat();
    			break;
    			
    			case 2:
    			SetupReverse();
    			break;
    			
    			default:
    			printf("Invalid Option");
    			break;
    			
    		}
    		
    		printf("\n\nPlease Select one of the following options: \n");
    		printf("1	Cats and Dogs\n");
    		printf("2	Reverse Text\n");
    		scanf("%d",&option);
    	}
    	return 0;
    }
    
    
    /*End
     * of
     * Main
     * */
    
    
    void dogcat(){
    	
    	int i;
        int array[100];
        
        for(i = 1; i <= 100; i++)
        {
            array[i] = i;
        }
    
    
        for(i = 1; i <= 100; i++)
        {
            if(array[i]%5 == 0 && array[i]%3 == 0){printf("dogcat ");}
            
            else if(array[i]%3 == 0){printf("cat ");}
            
            else if(array[i]%5 == 0){printf("dog ");}
            
            else{printf("%d ",array[i]);}
        }
    	
    }
    
    
    void SetupReverse()
    {
    	
    	int size = 1;
    	char *str;
    	str = (char*) malloc(size*sizeof(char));
    	
    	char c;
        
        int t = 0;
        int cnt = 0;
        int len;
    	
    		
    	printf("Please input a sentence: \n");
    		
    	
    	c = getchar();
    
    
        while(c!='\n') {
            if(cnt > size) {
                str = (char*) realloc(str,2*cnt);
            }
    		
            str[t] = c;
            c = getchar();
            t++;
            cnt++;
        }
    	
    	str[t]='\0';
    	
    	
    	
        printf("\nThe string is: \n %s \n",str);
        len = strlen(str);
    	
        printf("\nThe size is: \n %d \n\n",len);
    	
    	printf("\nThe string in Reverse is: \n \n");
    	
    	printReverse(str);
    	printf("\n\n");
    	
    	
    	free(str);
    	
    	
    	
    }
    
    
    void printReverse(char str[])
    {
        int length = strlen(str);
    	char newStr[length];
    	strcpy(newStr,str);
        // Traverse string from end
        int i;
        for (i = length - 1; i >= 0; i--) {
            if (newStr[i] == ' ') {
     
                // putting the NULL character at the 
                // position of space characters for
                // next iteration.          
                newStr[i] = '\0';
     
                // Start from next charatcer     
                printf("%s ", &(newStr[i]) + 1);
            }
        }
     
        // printing the last word
        printf("%s", newStr);
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    This happens because scanf leaves the newline character in the input stream, when reading certain kinds of input. You need to discard it, I usually either always read everything with fgets and parse the line with sscanf, or do this after every scanf that can leave the newline behind:
    Code:
    while ((c = getchar()) != '\n' && c != EOF)
        continue;
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Nov 2018
    Posts
    3
    I'm not using scanf in that function though

  4. #4
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by owtu View Post
    Hello, I have a question regarding the following code. I have two functions in it, one called SetupReverse() and the other printReverse(char str[])

    SetupReverse allocates memory for an user to enter a sentence. and printReverse takes that sentence and prints it in reverse. i.e. "C programming language is cool" becomes "cool is language programming C"

    It was working until I decided to include a switch case statement in main to make it more interactive and now it doesn't even prompt me to enter the sentence, it skips it completely. Why?
    in your functions SetupReverse()
    Code:
       printf("Please input a sentence: \n");
        // stops it dead cold. 
        getchar();
        //gets the input you're looking for.      
        c = getchar();
    just add that extra getchar to hold it in place for your input.
    Last edited by poorboy; 11-29-2018 at 02:27 PM.

  5. #5
    Registered User
    Join Date
    Nov 2018
    Posts
    3
    That worked! Thank you!

  6. #6
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Quote Originally Posted by owtu View Post
    I'm not using scanf in that function though
    This runs correct:

    Code:
    void dogcat();
    /*Sets up the text that will be reversed*/
    void SetupReverse();
    /*Reverses the text that was typed in SetupReverse() function*/
    void printReverse(char str[]);
    void flush_stdin (void);
    . . .
     int option;
        printf("Please Select one of the following options: \n");
        printf("1   Cats and Dogs\n");
        printf("2   Reverse Text\n\n");
        scanf("%d",&option);
        flush_stdin();
    . . .
    printf("\n\nPlease Select one of the following options: \n");
            printf("1   Cats and Dogs\n");
            printf("2   Reverse Text\n");
            scanf("%d",&option);
        flush_stdin();
        }
    return 0;
    
    void flush_stdin (void) 
    {
       int c;
       while ((c = getchar()) != '\n' && c != EOF);
       return;
    }
    (Display?)

    But how I come out of the program?

    switch case statement ignoring input from another function-dog-eat-dog2018-11-29_211750-jpg
    Last edited by Kernelpanic; 11-29-2018 at 02:29 PM.

  7. #7
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by owtu View Post
    That worked! Thank you!
    np,



    just a formatting suggestion to help you cut down from having to type so much redundant code.

    , in your main, putting the print out options message in only once, just after your while(1), because the way you have it written right now, it is always going to just fall into your loop then back around again to the top then printf again, Notice another way to print out multiple lines using only one printf
    Code:
      int option;
         
        while(1){
          printf("\n\nPlease Select one of the following options: \n"
                "1   Cats and Dogs\n"
                "2   Reverse Text\n");
                scanf("%d",&option);
            
            switch(option)
            {
    i too noticed that you have no means of exiting your program gracefully.
    Last edited by poorboy; 11-29-2018 at 02:33 PM.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > for(i = 1; i <= 100; i++)
    You're running off the end of the array.
    Subscripts start at 0, not 1.

    So perhaps
    for(i = 0; i < 100; i++)

    > str = (char*) malloc(size*sizeof(char));
    Don't cast the return result of malloc in a C program.
    FAQ > Casting malloc - Cprogramming.com

    Code:
            if(cnt > size) {
                str = (char*) realloc(str,2*cnt);
            }
    Three things wrong here.
    1. The test should be >=, because when cnt == size, you're stepping out of bounds.
    2. You don't change size to keep track of how big your array has become.
    3. If realloc fails, you have a memory leak.
    You should have
    Code:
    if(cnt >= size) {
        void *tmp = realloc(str,2*cnt);
        if ( tmp != NULL ) {
            str = tmp;
            size = 2 * cnt;
        } else {
            // str still points to the memory you had
        }
    Yet another off by 1 error
    Code:
        int length = strlen(str);
        char newStr[length];
        strcpy(newStr,str);
    newStr needs to be length+1
    Otherwise strcpy writes the \0 out of bounds.
    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. Switch Case statement with Strings
    By Supremezzy in forum C Programming
    Replies: 4
    Last Post: 04-19-2016, 01:44 AM
  2. Switch case statement does not execute
    By Joner in forum C Programming
    Replies: 1
    Last Post: 02-11-2013, 04:03 PM
  3. can you place a if/else statement in a switch case
    By swansea in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2010, 08:59 PM
  4. Replies: 11
    Last Post: 08-25-2008, 12:01 PM
  5. switch case statement
    By stanlvw in forum C++ Programming
    Replies: 3
    Last Post: 02-26-2008, 05:06 AM

Tags for this Thread