将用户输入存储到2D阵列并突破?

时间:2014-04-06 23:08:07

标签: arrays store nested-loops break

我正在做我的班级工作而且我坚持使用2D数组,嵌套循环并且在某些条件下爆发。

void main (){
int a;
int b;
int orders[100][4];
char confirm[50];


//printf("Enter the number of boxes of whistles you need on this invoice");
for (a = 0; a <=100; a++){
    for(b =0; b <4; b++){
    printf("Enter the number of boxes of whistles you need on this invoice");
    scanf("%d", &orders[a][b]);
    while (orders[a][b] <0)
    {
    printf("Invalid value! Please check the number.");
    scanf("%d", &orders[a][b]);
    }
    printf("Enter the number of boxes of bells you need on this invoice.");
    scanf("%d", &orders[a][b]);
    while (orders[a][b] <0)
    {
    printf("Invalid value! Please check the number.");
    scanf("%d", &orders[a][b]);
    }
    printf("Enter the number of boxes of horns you need on this invoice");
    scanf("%d", &orders[a][b]);
    while (orders[a][b]<0)
    {
    printf("Invalid value! Please check the number.");
    scanf("%d", &orders[a][b]);
    }

    printf("Do you want to enter more orders?");
    scanf("%s", confirm);
    if (strcmp(confirm, "N") == 1){
        break;
    }
}

如您所见,我应该用用户输入来填充2D数组(如果愿意,可以填写发票图表)。我不确定我的代码是否正确。最后,当用户说N为“No”时,我试图摆脱循环,而程序问“你想要输入更多订单吗?”当我尝试代码时,它会询问所有问题并且它似乎存储它但是即使我把N放在最后也无法摆脱循环。

所以...我的问题是

  1. 我的存储2D数组是否正确编码了用户输入?
  2. 当我说N(或任何其他字母或数字)时,如何摆脱循环(或结束循环)?
  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

我知道为别人做家庭作业很难过,但无论如何,我们走了。

阵列可能是动态的,没有固定的大小[100] [4]

清空您的阵列,否则它会充满您赢得的大量数据。

b仅在完成循环后增加。你甚至不需要循环,目前你的所有数据都写在完全相同的位置[a] [b]。考虑跳过该循环并编写[a] [0],[a] [1]等等。

当真实时,

strcmp(confirm, "N")返回0。

至于现在,你在一个双循环中。要解决此问题,您很可能希望将循环放在单独的函数中,然后调用return而不是break。从技术上讲,你现在也可以这样做,但是你会终止主函数。