C question console application windows

Joeado123

Well-Known Member
OP
Member
Joined
Mar 25, 2017
Messages
105
Trophies
0
Age
34
XP
483
Country
Canada
Hi, I am doing a plus or minus game (I'm actually learning how to code in c) and I had a problem. When I was typing letter instead of numbers, (The menu is all right it's covered with a switch) I was trying to guess the number I got "It's Bigger!" (this is what I wrote it's normal) but written a thousand times surely. Why is it doing this and how can I write letters without the need to close the program?
 

Joeado123

Well-Known Member
OP
Member
Joined
Mar 25, 2017
Messages
105
Trophies
0
Age
34
XP
483
Country
Canada
The case 1 of my switch (might help to know what's missing)


switch(Menu)
{
case 1:
printf("\nPlus or Minus level 1: between 1 and 100");
int MAX = 100, MIN = 0;
srand(time(NULL));
number1 = (rand() % (MAX - MIN + 1)+ MIN);
printf("\nType a number between 1 and 100:");
do
{
scanf("%d", &number2);


if (number1 < number2)
{
printf("It's less!");
meter++;
}

else if (number1 > number2)
{
printf ("It's more!");
meter++;
}

else
{
printf("You found the mystery number in %d times", );
meter = 0;
printf("\nDo you want to do another game?\nIf yes type 1, or 0 to quit: ");
scanf("%d", &Replay);
}
}while(number1 != number2);

break;
 

GerbilSoft

Well-Known Member
Member
Joined
Mar 8, 2012
Messages
2,395
Trophies
2
Age
34
XP
4,250
Country
United States
If you enter a letter, it fails the "%d" specifier, so scanf() returns 0 and doesn't set number2 to anything. You might want to try this instead:

Code:
char buf[128];
fgets(buf, sizeof(buf), stdin);
number2 = (int)strtol(buf, NULL, 10);
This uses fgets() to get a string from stdin (up to 127 characters plus NULL terminator), and then uses strtol() to convert it to a number.

Note that strtol() will return 0 if it's not a valid number.
 

Site & Scene News

Popular threads in this forum

General chit-chat
Help Users
    K3Nv2 @ K3Nv2: This movie rip so werid has 10180p quality but the audios ripped with movie theater audio quality