Frage

#define f(x) (x*(x+1)*(2*x+1))/6
void terminate();
main()
{
   int n,op;
   char c;
   printf("Enter n value\n");
   scanf("%d",&n);
   op=f(n);
   printf("%d",op);
   printf("want to enter another value: (y / n)?\n");
   scanf("%c",&c);   // execution stops here itself without taking input.
   getch();
   if(c=='y')
    main();
   else
    terminate();
   getch();

 }
void terminate()
{
exit(1);
}

In the program above , I want to take input from the user until he enters an n value. For this I'm trying to call main() function repeatedly . If it is legal in C , I want to know why the program terminates at the scanf("%c",&c) as shown in commented line. Someone , please help.

War es hilfreich?

Lösung

You should never call main from within your program. If you need to run it more then once use a while loop inside it.

Your execution stops because by default stdin in a terminal is line buffered. Also you are not using the return value from getch.

int main()
{
   int n,op;

    char c;
    do {
        printf("Enter n value\n");
        scanf("%d",&n);
        op=f(n);
        printf("%d",op);
        printf("want to enter another value: (y / n)?\n");
        scanf("%c",&c);
    } while (c == 'y')

    return 0;
}

Andere Tipps

You first have

scanf("%d",&n);

which you have to press the Enter key for it to accept the number.

Later you have

scanf("%c",&c);

There is a problem here, which is that the first call to scanf leaves that Enter key in the input buffer. So the later scanf call will read that.

This is easily solved, by changing the format string for the second scanf call just a little bit:

scanf(" %c",&c);
/*     ^           */
/*     |           */
/* Note space here */

This tells the scanf function to skip leading whitespace, which includes newlines like the Enter key leaves.

It's legal, but you'll have a STACKOVERFLOW after a while (pun intended). What you need is a loop:

while (1) {
  printf("Enter n value\n");
  scanf("%d",&n);
  op=f(n);
  printf("%d",op);
  printf("want to enter another value: (y / n)?\n");
  scanf("%c",&c);   // execution stops here itself without taking input.
  getch();
  if(c != 'y')
    break;;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top