rookie error 
Author Message
 rookie error

Hi everyone
   I wrote three simple functions to ask user enter something.
They are in the same format like following

int askN(void)
{
  int n = 0;
  printf("enter n-> ");
  scanf("%d", &n);
  return n;

Quote:
}

int askR(void)
{
  int r = 0;
  printf("enter r-> ");
  scanf("%d", &r);
  return r;

Quote:
}

the third one is

char doMore(void)
{
  char ans;
  printf("enter (Y/N)-> ");
  scanf("%c",&ans);
  return ans;

Quote:
}

Now my question is when I called this three funcitons in main(),
the order really matterd.  Why??

int main(void)
{
  int n, r;
  char answer;

  n = askN();
  printf("you entered %d\n", n);
  r = askR();
  printf("you entered %d\n", r);
  answer = doMore();
  printf("you entered %c\n", answer);

  return 0;

Quote:
}

the order above caused problem. It won't let the user enter anything and
it just printed the following message.
But if I call the doMore() before the other two functions, it works fine.
It seems something is inside my standard input buffer. so my scanf() just
grabed that and printed next message.
I can not figure out why it behaves in this way.
thanks a lot, guys.


Sat, 02 Apr 2005 08:35:46 GMT  
 rookie error

Quote:

> the order above caused problem. It won't let the user enter anything and
> it just printed the following message.
> But if I call the doMore() before the other two functions, it works fine.
> It seems something is inside my standard input buffer. so my scanf() just
> grabed that and printed next message.

scanf() won't skip trailing whitespace, so %c will read a
new-line.
--
"It would be a much better example of undefined behavior
 if the behavior were undefined."
--Michael Rubenstein


Sat, 02 Apr 2005 08:43:52 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. hopelessly lost c rookie!!!

2. Rookie C programmer need help!

3. rookie question2

4. rookie question

5. a question from a rookie in C

6. rookie question

7. Rookie Needs Path

8. Rookie Help

9. <rookie post> program hangs

10. rookie problem: problem with LNew function

11. Rookie

12. rookie extern linking question

 

 
Powered by phpBB® Forum Software