Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,696 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,498 people online right now. Registration is fast and FREE... Join Now!




Handling User Input

 
Reply to this topicStart new topic

Handling User Input

Jeune
post 20 Dec, 2005 - 02:43 AM
Post #1


New D.I.C Head

*
Joined: 20 Dec, 2005
Posts: 1


My Contributions


Hi guys!

I need help with a simple C program I am doing.
I want the program to do something then ask the user if it wants to do it again.
I used a do-while loop for this but as it comes out it's either a bug or there's something I really need to know.

Here is my code btw:

CODE

#include <stdio.h>

main()
{
   char a='y';
   int b;

  do
  {
          printf("\nEnter a number: ");
          scanf("%d",&b);
          printf("You entered %d\n\n",b);
           
          printf("try again? (y/n): ");
          scanf("%c",&a);
          printf("\n");

  } while (a!='n');
}


I have a problem with my code and it this is what happens:

Enter a number: 5
You entered 5

try again?(y/n):

Enter a number: _ <---------- cursor

It does not ask if the user tries again. Instead, it goes directly to asking the user too input a new number.

Has anyone encountered this problem before?
I really need help.

Thanks
User is offlineProfile CardPM

Go to the top of the page


Amadeus
post 20 Dec, 2005 - 07:32 AM
Post #2


g++ -o drink whiskey.cpp

Group Icon
Joined: 12 Jul, 2002
Posts: 12,163



Thanked 32 times

Dream Kudos: 25
My Contributions


I expect you'll find many who have encountered the problem...it's pretty common. It stems from the fact that scanf() is usually not a good choice for getting user input in a loop, as it reads from the stream...there is a slight difference between the stream and the screen you see.

You first ask the user for a number, which they choose, and then press enter. The stream, however, now contains that number and a newline character (from the enter action). You process the number, and then ask for a character, and use scanf. Problem is, scanf() reads from the stream, so there is already a newline character queued up and ready to go, which it reads and processes instead of waiting for new input.

If looking for character input in a loop, it's usually better to go with a fgets/fputs type of option...sometimes even getchar().

Here is a good example.
User is online!Profile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 11/20/08 08:41AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month