arniem
arniem

Reputation: 145

C program exits without any prompt

The following code should accept input from the user- an array of size USERDEFINED and then print it. Following that, it should wait for an input from the user to exit the program, which is defined in the function waitUntill. But it does not work as intended. It just prints "PRESS ENTER TO EXIT" and exits without accepting any input. What am I doing wrong here ?

#include <stdio.h>
#include <stdlib.h>


void waitUntill();

int main()
{
  int arrSize = 0;
  int array[arrSize];

  printf("\nWhat size of array do you want: ");
  scanf("%d", &arrSize);

  printf("\nEnter %d numbers: ", arrSize);
  for(int i = 0; i < arrSize; i++)
  {
    scanf("%d", &array[i]);
  }
  printf("\nYour array is:\t");
  for(int i = 0; i < arrSize; i++)
  {
    printf("[%d]", array[i]);
  }
  waitUntill();
  return 0;
}

void waitUntill()
{
  printf("\n\nPRESS ENTER TO EXIT !!!\n");
  while(1)
  {
    if (getchar())
      break;
  }
  printf("\n");
}

Upvotes: 0

Views: 333

Answers (3)

Ankit Srivastava
Ankit Srivastava

Reputation: 21

void waitUntill()
{
  printf("\n\nPRESS ENTER TO EXIT !!!\n");
  while(1)
  {
    fflush(stdin);
    if (getchar())
      break;
  }

  printf("\n");
}

But Why you need that infinite loop, your code could be as simple as below:

void waitUntill()
{
  printf("\n\nPRESS ENTER TO EXIT !!!\n");
  fflush(stdin);
  getchar();
}

Upvotes: 1

anastaciu
anastaciu

Reputation: 23792

I believe getchar() catches the last \n, of the previous string, you can use it twice:

void waitUntill()
{
    printf("\n\nPRESS ENTER TO EXIT !!!\n");
    while(1)
    {
        if (getchar() && getchar())
            break;
    }
    printf("\n");
}

I don't know why you need that infinite cicle, if it's just to catch a random inserted char your function can be simpler:

void waitUntill()
{
    printf("\n\nPRESS ENTER TO EXIT !!!\n");
    getchar();
    getchar();
    printf("\n");
}

Upvotes: 1

0___________
0___________

Reputation: 67476

You need to allocate the array after you read its size;

void waitUntill();

int main()
{
  int arrSize = 0;
  int *array;

  printf("\nWhat size of array do you want: ");
  scanf("%d", &arrSize);

  array = malloc(arrSize * sizeof(*array));
  if(array)
  {
    ....
    waitUntill();
    free(array);
  }
  return 0;
}

void waitUntill()
{
  printf("\n\nPRESS ENTER TO EXIT !!!\n");
  while(1)
  {
    if (getchar())
      break;
  }
  printf("\n");
}

Upvotes: 1

Related Questions