thanx man! But the program should also quit if there are more than two inputs. I can see the program discards additional inputs but i want it to exit for more than two inputs.
There are several ways. I would prefer to respond to one that says, "I've tried this <insert code>, but it doesn't do what I expect." But...
#include <stdio.h>
int main(void)
{
int a,b,n;
char line [ BUFSIZ ];
for ( ;; )
{
fputs("Enter two integers: ", stdout);
fflush(stdout);
if ( fgets(line, sizeof line, stdin) )
{
if ( sscanf(line, "%d%d%n", &a, &b, &n) == 2 && line [ n ] == '\n')
{
break;
}
}
puts("try again");
}
printf("a = %d, b = %d\n", a, b);
return 0;
}
/* my output
Enter two integers: 1
try again
Enter two integers: 1 2 3
try again
Enter two integers: a b
try again
Enter two integers: 1 2a
try again
Enter two integers: 1 2
a = 1, b = 2
*/
Reputation Points: 2780
Solved Threads: 312
long time no c
Offline 4,790 posts
since Apr 2004