One way:
#include <stdio.h>
int main(void)
{
int a,b;
char line [ BUFSIZ ];
for ( ;; )
{
fputs("Enter two integer: ", stdout);
fflush(stdout);
if ( fgets(line, sizeof line, stdin) )
{
if ( sscanf(line, "%d%d", &a, &b) != 2 )
{
return 0;
}
printf("a = %d, b = %d\n", a, b);
}
}
return 0;
}
/* my output
Enter two integer: 12 45
a = 12, b = 45
Enter two integer: 11
*/
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
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 , 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
*/
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314