简体   繁体   English

程序突然结束,在 C 中的 while 循环中带有 switch case

[英]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.我有这个程序显示,它允许我显示一个有 3 个选项的菜单。 If you choose anything except exit (0) then the program continues to loop.如果您选择退出(0)以外的任何内容,则程序将继续循环。

However, when I try to call a function from inside the switch statement, once the function is finished, the loop exists completely.但是,当我尝试从 switch 语句内部调用函数时,一旦函数完成,循环就完全存在。 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.如果我选择 2,三角形,它也可以工作,然后它会留在循环中。

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!您从stdin读取了一个数字,但您将尾随的换行符留在了流中!

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.number设置为0 ,导致程序退出。

One possible fix would be to read in rows with fgets() and atoi() as you do it with number .一种可能的解决方法是使用fgets()atoi()读取rows ,就像使用number

The problem is this call in the function xmasTree问题是函数xmasTree中的这个调用

scanf("%d",&rows);

After it there is stored the new line character '\\n' in the buffer.在它之后,在缓冲区中存储了换行符'\\n' So the next call of the function fgets reads an empty string.所以函数fgets的下一次调用读取一个空字符串。 You should remove this new line character as for example例如,您应该删除此新行字符

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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