Hi,
i have a program that asks the user for a number and i want it to give an error message when the user enters a letter. Until now it freezes when that happens. I know that's a noob question but can anybody help me please?
Hi,
i have a program that asks the user for a number and i want it to give an error message when the user enters a letter. Until now it freezes when that happens. I know that's a noob question but can anybody help me please?
Show us the code you're using (don't forget to use code tags) so that we can help you out.
Thanks for your attention .Code:#include <stdio.h> #include<stdlib.h> int main(void) { int horasdepijama; printf("Quantas horas por dia, em media, passa o mora de pijama?\n"); scanf("%d", &horasdepijama); while (horasdepijama !=22){ if (horasdepijama < 22){ system("cls"); printf("Errado\n"); printf("Lembra-te, e o mora. Tenta um valor superior\n"); printf("\n"); } else if (horasdepijama == 23){ system("cls"); printf("Errado\n"); printf("Ok e o mora, mas ainda nao e tanto. Tenta um valor inferior\n"); printf("\n"); } else if (horasdepijama == 24){ system("cls"); printf("Errado\n"); printf("Ok e o mora, mas ainda nao e tanto. Tenta um valor inferior\n"); printf("\n"); } else if (horasdepijama > 24 && horasdepijama != 'a'){ system("cls"); printf("Burro!\n"); printf("Um dia so tem 24horas!\n"); printf("\n"); } printf("Quantas horas por dia, em media, passa o mora de pijama?\n"); scanf("%d", &horasdepijama); } if (horasdepijama == 22){ system("cls"); printf("CERTO! 22horas de pijama! Que bela criatura!\n"); printf("\n"); printf("As restantes sao 1 para ir ao cafe e outra para tomar banho\n"); printf("\n"); printf("By: JOAO GASPAR\n"); } system("PAUSE"); return 0; }
Try checking the return value of scanf.
Try doing this at the end of your loop.
Code:printf("Quantas horas por dia, em media, passa o mora de pijama?\n"); fflush(stdin); scanf("%d", &horasdepijama);
No! Do NOT do that. It's undefined behavior, and likely wont work at all, unless you're still using that 20 year old piece of crap Borland Turbo C compiler (which you should stop doing immediately and upgrade to something decent). Read the FAQ on why it's wrong and how to fix it:
Cprogramming.com FAQ > Why fflush(stdin) is wrong
Cprogramming.com FAQ > Flush the input buffer
By way of expanding on the above... scanf() does pattern matching on the keyboard buffer... the return value is the number of conversions it completed... so if you're asking for numbers ( %d ) and it gets letters, the return value will be 0.
(Added because the documentation isn't always clear about this)
The example given is with the var type 'char' and my code is with the 'int' type. I'm trying adjust it but i'm not doing it right. Can somebody get me an example with a code more like my own?
Hope is the first step on the road to disappointment.
Check out int isalpha() or int isdigit() of the ctype header.