【问题标题】:Can someone please look at my queue?有人可以看看我的队列吗?
【发布时间】:2014-08-10 06:22:00
【问题描述】:

我正在使用开发 C++。当我在队列中输入一个名字并按下回车键时,程序就会崩溃

void queue (Client c[])
{
    int choice,tail=0,max=20,front=0,ch,w;
    char queue [20];

    do {
        printf ("Do You Want To (1)Enter Clients To A Queue or (2)Remove Clients From A Queue?");
        scanf ("%d",&choice);
    }while (choice<1 || choice>2);

    if (choice==1)
    {
        if (tail==max-1)
        {
            printf("Queue is full!");
            return;
        }

        tail++;
        printf("Enter Client Name:");
        scanf (" %[^\n]",queue[tail]);            
        if (front==-1)
            front++;
    }
    else if (choice==2)
    {
        if (front==-1)
        {
            printf("Queue is empty!");
            return;
        }
        printf("Enter Client Name To Remove:");
        scanf (" %[^\n]",queue[front]);
        if (front==tail)
            front=tail=-1;
        else
            front++;
    }

    do {
        printf ("Do You Want To (1)Queue More Clients or (2)Continue?");
        scanf ("%d",&ch);
    }while (ch<1 || ch>2);

    if (ch==1)
    {
        void queue (Client []);
        queue (c);
    } 
    else if (ch==2)
    {
        do{
            printf ("Do You Want To Go Back To (1)The Main Menu Or (2)Exit?");
            scanf ("%d",&w);
        }while (w<1 || w>2);

        if (w==1)
        {
            void main_menu (Client[]);
            main_menu (c);   
        }
        else if (w==2)
        {
            void end (Client []);
            end (c);
        }
    }                 
}

【问题讨论】:

  • 开启警告...

标签: c function queue


【解决方案1】:

您需要一个多维字符数组来保存名称。您要做的是接受单个字符的名称。怎么可能?

只需更改代码:

char queue [20];

到:

char queue [20][20];

【讨论】:

  • 另外,对于 20 个元素的队列,您只能使用 0-19 个索引。队列[20] 不存在。
  • 是的。确切地。但我只是建议他使用二维字符数组,以便他可以在该队列应用程序中使用。现在大小取决于程序员他/她想要多少记录。
【解决方案2】:

这里好像有问题:

printf("Enter Client Name:");
scanf (" %[^\n]",queue[tail]);

您正在尝试将名称(这是一个字符数组)输入到队列的一个元素(这是一个字符)。也许你应该把它改成:

printf("Enter Client Name:");
scanf (" %[^\n]",queue);

您的代码还有改进的余地。需要测试的一些重要事项:

  1. 为您的队列变量使用不同的名称(将其与您的队列方法区分开来)。
  2. 您的队列变量应该在函数中而不是全局声明。
  3. 你的队列变量应该是这样的:char* queueVariable[20];它应该是一个名称数组(它本身就是一个字符数组)。
  4. 队列绑定控制器变量也应该全局声明。

【讨论】:

    猜你喜欢
    • 2015-01-20
    • 1970-01-01
    • 2016-03-03
    • 2021-10-13
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多