接受数组输入,直到输入某个值

时间:2017-07-30 02:15:55

标签: c

如果输入值-1,如何停止接受数组的输入?

这是我接受输入的代码。我的想法是我需要在for循环之前输入do while循环,但我不知道如何写出来。

void getdataset(int[]);


int main()
{
  int dataset[LENGTH];

  getdataset(dataset);

  return(0);
}

void getdataset(int dataset[])
{
  int lcv;

  printf("Enter up to 25 values or -1 to exit: ");
  for(lcv = 0; lcv < LENGTH; lcv ++)
  {
    scanf("%d", &dataset[lcv]);
  }
}

4 个答案:

答案 0 :(得分:1)

我建议使用以下代码。

#include <stdio.h>

#define LENGTH 25
#define EOI -1 //End Of Input

size_t getdataset(int array[], size_t array_size);

int main(void){
    int dataset[LENGTH];

    size_t n = getdataset(dataset, LENGTH);//Pass the size of the array

    //check print
    for(int i = 0; i < n; ++i)
        printf("%d ", dataset[i]);
    puts("");

    return 0;//You do not need parentheses.
}

size_t getdataset(int dataset[], size_t array_size){
    size_t c;//Count actual input.
    int v;

    printf("Enter up to %d values or %d to exit:\n", LENGTH, EOI);

    for(c = 0; c < array_size && scanf("%d", &v) == 1 && v != EOI; ++c)
        dataset[c] = v;//Error handling may be necessary.

    return c;//To omit the code, return the actual number of inputs.
}

答案 1 :(得分:0)

break是你的朋友。它允许你强制退出while循环,for循环或do ... while循环(但是如果嵌套则只有一个循环)(或switch语句)。

因此,您可能希望在每个循环中scanf之后添加此行。

if (dataset[lcv] == -1)
    break;

如果您不想使用break来中断循环,请添加自定义循环检查。

int flag = 1;
for(lcv = 0; flag && lcv < LENGTH; lcv ++)
{
    scanf("%d", &dataset[lcv]);
    if (dataset[lcv] == -1) flag = 0;
}

答案 2 :(得分:0)

break是一个非常好的答案,但您也可以使用goto,有时候会更好:

void getdataset(int dataset[])
{
  int lcv;
  printf("Enter up to 25 values or -1 to exit: ");
  for(lcv = 0; lcv < LENGTH; lcv ++)
  {
    scanf("%d", &dataset[lcv]);
    if (lcv[dataset] == -1) goto exitloop;
  }
  exitloop:;
}

在上一个示例中,break优于goto

但是当你有嵌套循环时,gotobreak更好:

void getdataset(int dataset[])
{
  int lcv, i;
  printf("Enter up to 25 values or -1 to exit: ");
  for(lcv = 0; lcv < LENGTH; lcv ++)
  {
    for (i = 0; i < 1; i++)
    {
      scanf("%d", &dataset[lcv]);
      if (lcv[dataset] == -1) goto exitloop;
    }
  }
  exitloop:;
}

答案 3 :(得分:0)

另一种不使用中断的方法:

int i = 0, lcv = 0;

while (scanf("%d", i), ((i != -1) && (lcv < LENGTH)) {
    dataset[lcv++] = i;
}

这使用了逗号运算符,这个运算符并不是很多人所熟悉的: https://en.wikipedia.org/wiki/Comma_operator

或者,以for循环形式:

int i = 0;

for (int lcv = 0 ; scanf("%d", i), ((i != -1) && (lcv < LENGTH)) ; lcv++)
{
    dataset[lcv] = i;
}