-1

This a C program that I wrote for an assignment. I just wanna add some lines of code of my own. But it ended up in a never-ending loop.

I tried using a while loop to solve this, but that is where my problem is.

int tab1[6],c;

printf("\n\nEnter 4 integers in the first array:\n ");

for (c = 0; c < 4; ++c)
{
    printf("\n\tValue %d : ",c+1);
    scanf("%d",&tab1[c]);
        //if tab1[c] is not a number ask again.
            while (!isalpha(tab1[c]))
            { 
                printf("nEnter an integer : ");
            }
            scanf("%d",&tab1[c]);

}

I wanted for the program to ask out for an integer when the user enter something other than an integer.

dyerlin
  • 1
  • 2
  • 1
    Even if what you were trying to do could work, you have the second `scanf` outside the `while` loop. Since the condition being tested never changes, you get an infinite loop. – Barmar Apr 19 '19 at 17:25

1 Answers1

0

You need to do the conversion from string to number after getting the input. I mean: first input, then check and convert.

// 1st: input
if (!fgets(buf, sizeof buf, stdin)) /* error */;
// 2nd: check and convert
if (sscanf(buf, "%d", &tab1[c]) != 1) /* error */;

scanf() is already doing that on its own, but you maybe want something more powerful.

You want to use the return value of scanf() to know whether it converted successfully:

if (scanf("%d", &tab1[c]) != 1) /* error */
pmg
  • 106,608
  • 13
  • 126
  • 198