简体   繁体   中英

Program ends suddenly, with switch case inside while loop in C

I have this program show, which allows me to display a menu with 3 choices. If you choose anything except exit (0) then the program continues to loop.

However, when I try to call a function from inside the switch statement, once the function is finished, the loop exists completely. I want to go back to the menu and continue unless I select exit.

The program works, without the function call. It also works if I select 2, triangle, it then stays in the loop.

Why is this happening, and how can I fix it,

many thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int rows;

void xmasTree(void)
{ 
 printf("Enter Rows:\n>");
 scanf("%d",&rows);
}

int main (int argc, char ** argv)
{
    int flag = 1;
    while (flag)
    {
        //Print menu
        printf("1: Create xmas tree\n");
        printf("2: Create triangle\n");
        printf("0: exit\n");
        printf("Enter choice :");
        //read input
        char buffer[10];
        fgets(buffer, 10, stdin);
        //convert to number
        int number = atoi (buffer);

        //work on input
        switch (number)
        {
            case 1:
                printf("Building your xmas tree\n");
                xmasTree();
                break;
            case 2:
                printf("creating your triangle\n");
                break;
            case 0:
                printf("Exiting...\n");
                flag = 0;
                break;
            default:
                printf("INVAID INPUT\n");
                break;
        }
    }   
    return 0;
}   

The problem is, that here

scanf("%d",&rows);

you read a number from stdin , but you leave the trailing newline inside the stream!

Then, in the next loop iteration

fgets(buffer, 10, stdin);

reads the (empty) line and

int number = atoi (buffer);

sets number to 0 , causing your program to exit.

One possible fix would be to read in rows with fgets() and atoi() as you do it with number .

The problem is this call in the function xmasTree

scanf("%d",&rows);

After it there is stored the new line character '\\n' in the buffer. So the next call of the function fgets reads an empty string. You should remove this new line character as for example

scanf("%d",&rows);
scanf( "%*[^\n]" );
scanf( "%*c" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM