I started a random numbers game and got it all done. Then I realized that if you entered a letter instead of a number it crashes the game.
What is the code to help stop that from happening?
I started a random numbers game and got it all done. Then I realized that if you entered a letter instead of a number it crashes the game.
What is the code to help stop that from happening?
Post your code here (in code tags, please)... There could be several solutions.
I think I posted this right lol
Code:#include<stdio.h> #include<stdlib.h> #include<time.h> void main() { int num,guess=-1,tries=0,pass=0; time_t t; srand((unsigned)time(&t)); num=rand()%100; while((guess!=num)&&tries<8) { printf(“Enter the guess num b/w 0 & 100 (you have %d tries left out)\n”,(8-tries)); scanf(“%d”,&guess); tries++; if(guess==num) { printf(“Hurray you guessed it correctly!!!\n”); pass=1; } else if(num< guess) printf(“Your guess is too high\n”); else printf(“Your guess is too low\n”); } if(pass==0) printf(“Sorry you lost! The correct number is %d\n”,num); }
Let's start with the basics:
1) void main should be int main(void) and should return 0 at the end of the function.
2) your indentation is horrible
3) you can read the input as a char and if it is not in the ASCII range you want to just tell the user his input is wrong.
1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
3. Get rid of conio.h and other antiquated DOS crap headers.
4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.
Has it happens, I've got just the two links you need already open.
SourceForge.net: Indentation - cpwiki
SourceForge.net: Void main - cpwiki
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.