Thread: how do I keep taking input over and over and store it into an array?

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    27

    how do I keep taking input over and over and store it into an array?

    for ex. lets say I have the code:

    Code:
    printf("\nEnter a number");
                      scanf("%d*c*");
    I want it to keep asking that over and over until someone presses a specific character to quit out.

    So it would say

    Enter a number:

    then you put in a # and after the # is entered it repeats again

    Enter a number:

    and the only way it exits out is if you type in something specific like 'X'.

    I think that can be done with a while loop

    Code:
    int n;
                 
                      printf("\nEnter a number");
                      scanf("%d*c*",&n);
                      while (n = 'X')
                  {
                      //code here that returns me to the main menu
                   }

    I am not very good with arrays but I want to store all the input into an array. .

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    You're going to need to put the statements inside the loop body. Then you just use your "special number" as an exit condition of the loop, combined with the upper bound of your array. In your example n is just an int, it needs to be an array.

    Here's the basic idea, where SIZE is a constant defining you array size and upper bound.

    Code:
    int i, a[SIZE] = {0};
    
    for(i = 0; i < SIZE; i++) {
        printf("Enter a number: ");
        scanf("%d", a+i);
        if(a[i] == -1)
            break;
    }

Popular pages Recent additions subscribe to a feed