gpt4 book ai didi

c - 读取数组中的输入,存储-1值,并在输入-1时退出?

转载 作者:行者123 更新时间:2023-11-30 18:50:48 24 4
gpt4 key购买 nike

我正在尝试制作一个程序,首先用一个菜单提示用户,菜单选项从 0 到 7 开始。

我有一个 switch 语句来检查输入的数字。该程序尚未完成我开始使用“构建列表选项”,其中用户输入值以将其存储到数组中,当用户输入“-1”时,我希望它将-1存储在数组还存储用户输入的数字。

问题是:程序不会一直提示用户输入数字,直到输入“-1”为止。相反,它将显示下一个菜单选项并退出。

#include <stdio.h>
#include <stdlib.h>
#define SIZE 50

void main ()
{
int i = 0;
int userinput[SIZE];
int x = 0;

do
{
printf("===DSCI0====\n");
printf("0. Build List\n");
printf("1. Display List Forward\n");
printf("2. Display List Backwards\n");
printf("3. Insert into list\n");
printf("4. Append into list\n");
printf("5. Obtain from List\n");
printf("6. Clear List\n");
printf("7. Quit\n");
printf("What is your menu option?\n");
scanf("%d", &i);

} while(i < 0 || i > 7);

switch(i)
{
case(0) :
for (x = 0; x < SIZE; x++);
{
printf("Enter a value for ther array (-1 to quit): \n");
scanf("%x", &userinput[x]);
if(userinput[x] == -1)
{
break;
}
}

case(1) : printf("Display List Fwd\n");
break;
case(2) : printf("Display List Bkwd\n");
break;
case(3) : printf("Insert into list\n");
break;
case(4) : printf("Append into list\n");
break;
case(5) : printf("Obtain from list\n");
break;
case(6) : printf("Clear List\n");
break;
case(7) : printf("Good-Bye\n");
exit(0);
break;
default : printf("Enter a value 0-7\n");
exit(0);
break;
}

}

更新:

我得到的解决方案帮助我在数组中输入数字。但是,当我尝试读出它时,我没有得到输入的值。

switch(i)
{
case(0) :
for (x = 0; x < SIZE; x++)
{
printf("Enter a value for ther array (-1 to quit): \n");
scanf("%x", &userinput[x]);
if(userinput[x] == -1)
{
break;
}
}

case(1) :
for (x = 0; x < SIZE; x++)
{
printf("[%i.] %i\n", i + 1, &userinput[x]);
if(userinput[x] == -1)
{
break;
}

本例中我的输出是:

What is your menu option?
0
Enter a value for the array (-1 to quit):
0
Enter a value for the array (-1 to quit):
1
Enter a value for the array (-1 to quit):
2
Enter a value for the array (-1 to quit):
3
Enter a value for the array (-1 to quit):
-1

1. 698667216
1. 698667216
1. 698667216
1. 698667216
Display List Bkwd

这可能是什么原因造成的?

最佳答案

删除最后一个分号

for (x = 0; x < SIZE; x++);

为了将循环后面的 block 放在循环内,并使系统迭代该 block 。

然后,在要迭代的 block 后面添加 break;,以免系统继续显示下一个菜单。

另请注意,您应该在托管环境中使用标准 int main(void) 而不是 void main(),这在 C89 中是非法的,在 C99 中是实现定义的或更高版本,除非您有特殊原因需要使用非标准签名。

回答更新的问题:

printf("[%i.] %i\n", i + 1, &userinput[x]);

将调用未定义的行为,因为将错误类型的数据传递给printf():%i调用int,但 &userinput[x] 类型为 int*。使用不带 &userinput[x] 来打印数组的内容。

关于c - 读取数组中的输入,存储-1值,并在输入-1时退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39008315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com