printf(" please insert integer number " );
scanf("%d",&k))
if user insert character or alphabet, the program will hang there.
So, do anybody can suggest how to over this problem.
Thanks
printf(" please insert integer number " );
scanf("%d",&k))
if user insert character or alphabet, the program will hang there.
So, do anybody can suggest how to over this problem.
Thanks
Code:#include <stdio.h> //Necessary for all programs to work int main(void) { //Necessary for all programs to work int k; //You must initialize your variables printf("Please insert an integar.\n"); //Follow proper printf format scanf("%d", %k); //same for scan f return 0; //must include } //must include
Read a string instead, and then use atoi on it to get the integer.
>Read a string instead, and then use atoi on it to get the integer.
So tell me. How is the nonexistent error handling and potential undefined behavior of atoi any improvement?
>So, do anybody can suggest how to over this problem.
It depends on what you're doing. In most cases your best bet is to read a line using fgets, validate your input as necessary, and make the appropriate conversions. Alternatively you could simply discard any input in the stream buffer and try again if scanf fails. Can you be more specific about your needs?
My best code is written with the delete key.
Yes it's a hack, but at least it won't give crazy values.
>Yes it's a hack, but at least it won't give crazy values.
You must have a different concept of undefined behavior than I do. Though I will agree that if the user enters non-numeric characters, atoi is very predictable in returning 0.
By the way, a hack is clever. This is just stupid because you're effectively putting on blinders and pretending that broken code is working.
My best code is written with the delete key.
A hack can also be something put together in a crude manner, which is what I was thinking of. I didn't know that atoi() had an undefined error handling, so how about strtol() or sscanf()?
Not really. When something is considered a hack, yes it's done in a crude manner, but it still gets the job done correctly. It may not be fast or efficient and it may be horribly sloppy to work with, but the eventual product works.Originally Posted by OnionKnight
Sent from my iPadŽ
How does that differ from what I said? When you "hack something together" you're doing it with speed so naturally things like error checking gets left behind.
Let's not turn this thread into a debate about the definition of hack and keep it on topic?
if you have int k, change it to char k. then %c instead of %d.Originally Posted by s3ng
I dont know what everybody else got into, but they made it way too complicated.
I assumed tat u have include the neccessary header files *.h.Originally Posted by s3ng
This is the correct format ------ scanf("%d",&k); <====Take note of the brackets and the semi-colon.