In my program i will be taking two inputs, lets say two integers. If the number of input is more than two the program will exit. If it is two then the loop will be executed and after that it will again ask for two new inputs-- and will continue this way. How do I accomplish this in PURE C(no C++)? I know this is not necessary to do in any sort of program, but asking just out of curiosity.

Another ques: also how do I clear the input stream in C(not clrscr())?

Recommended Answers

All 5 Replies

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
 */

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.

easy.
You can use 'exit(0)' instead of 'return 0'

easy.
You can use 'exit(0)' instead of 'return 0'

What are u talking about? I dont see how replacing 'return 0' with exit(0) in the program provided by dave makes any difference.

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
 */
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.