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

Join 86,390 C++ Programmers. There are 1,374 online right now! Ask your question and get quick answers from Dream.In.Code experts. Join the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a C++ Expert
Powered by LivePerson.com

Register to Make This Box Go Away!

newbie: get char input from keyboard

 
Reply to this topicStart new topic

newbie: get char input from keyboard

cuongvt
post 8 May, 2008 - 09:17 PM
Post #1


New D.I.C Head

*
Joined: 5 May, 2008
Posts: 2



I'm very new to C language, I have the following code:
#include <stdio.h>
#include <stdlib.h>
int number;
int total;
int nums=0;
int i;
char c;
int main()
{

for(;;)
{
printf("please enter number here, and character k to quit:\n");
fflush(stdin);
scanf("%d",&number);
total +=number;
nums++;

}

printf("average value: %d\n",total/nums);
return(0);
}

Now I want is that when user type 'k' from keyboard, above loop will break.
Could anyone modofy my source code so that I can learn from you?
Thanks and regards,


This post has been edited by cuongvt: 8 May, 2008 - 09:22 PM
User is offlineProfile CardPM
Go to the top of the page
+Quote Post


no2pencil
post 8 May, 2008 - 09:31 PM
Post #2


DIC K-mart

Group Icon
Joined: 10 May, 2007
Posts: 3,324

Rather than use the for loop, use a conditional while:

cpp

int ch;

while (ch!='k') {
printf("please enter number here, and character k to quit:\n");
fflush(stdin);
ch = getc(stdin);
if(isdigit(ch)) number=ch;
//scanf("%d",&number);
total +=number;
nums++;
}
User is online!Profile CardPM
Go to the top of the page
+Quote Post

cuongvt
post 9 May, 2008 - 06:12 AM
Post #3


New D.I.C Head

*
Joined: 5 May, 2008
Posts: 2

thank you smile.gif As newbie I learned a lot from you smile.gif
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
Time is now: 5/17/08 04:57AM

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