plz help with endless loop on failure

i am writing a homework and i try to make a loop that check the data input from user to be only positive int
i search a lot and i read some thing and i decide to try it but i fail

when i enter a char the program go to an endless loop

thank in advance

here is my program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    int i,j,a,num;
    char term;
    int C[3][3];
    puts("give a number: \t");
    for (i=0; i<3; i++)  
    {
        for(j=0; j<3; j++)
        {       
                  if((scanf("%d%c", &a, &term) != 2 || term != '\n') || a<0)
                  {
                         printf("you must give a positive number\n");
                         j--;
                  }
                  else
                  {
                         C[i][j]=a;
                  } 
         }
     }

     for (i=0; i<3; i++) 
     {
         printf("\n");
         for(j=0; j<3; j++)
         {
                  printf("%d\t",C[i][j]);
         }
         printf("\n");
     }
     system("PAUSE");
}

Last edited on
any help?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <climits>
using namespace std;

int main()
{
  int a = -1;
  while (a < 0)
  {
    cout << "Enter positive integer" << endl;
    cin >> a;
    cin.clear();
    cin.ignore(INT_MAX,'\n');
  }
  cout << "You entered " << a;
}
      
Last edited on
The equivalent if you must stick with C code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int main()
{
	int a = -1 ;

	while ( a<0 )
	{
		printf("Enter a positive integer\n");
		scanf(" %d", &a) ;
		scanf("%*[^\n]") ; 
	}

	printf( "You entered %d", a );
} 

thnks you so much both of you!!!!!!!!!!!
Topic archived. No new replies allowed.