2016-08-18 78 views
-1

我想做一个程序,第一次提示菜单的菜单选项从0到7开始菜单选项。在数组中读取输入,存储-1值并在输入-1时退出?

我有一个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 

可能是什么造成的?

回答

2

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

为了把块内循环的循环后,取下最后分号,造成系统迭代块。

然后,在块之后添加break;以迭代,以便不让系统继续显示下一个菜单。

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

要回答最新的问题:因为有错误的类型数据传递到printf()

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

将调用未定义行为%i呼吁int,但&userinput[x]是类型int*。使用userinput[x]而不使用&可以打印数组的内容。

+0

谢谢,我让那部分工作完美!不过,我在尝试打印出数组内容时遇到了一个错误 – sss34

+0

@Stan我更新了我的答案。 – MikeCAT

相关问题