I've been trying to make a small calculator program to test my own skills, due to me being pretty green when talking about coding. Anyways I'm trying to make a function with a loop that will ask for a number until a number is inputted and reject letters.
This is what my limited understanding/googling produced:
int is_number(int num){
do {
printf("\n:");
scanf("%d",&num);
if( isalpha(num)){
printf("\nYou entered a letter, please input a number\n");
continue;
} else {
printf("Number accepted...\n");
break;
}
} while(isalpha(num));
return num;
}
The only problem is that it crashes if given a letter, but there is progress... no infinitive spam of same message.
The next code is the whole code not just a snippet:
#include<stdio.h>
#include<windows.h>
#include<ctype.h>
//Records the answer for Y/N question and checks if answer is Y or No
char check_yesno_question(char a){
do{
printf("\n:");
scanf(" %c",&a);
if((a=='Y')||(a=='N')||(a=='y')||(a=='n')){
break;
}
else{
printf("\nIncorrect answer, please input Y or N (Y = Yes, N = No)\n");
continue;
}
}while((a!='Y')&&(a!='N')&&(a!='y')&&(a!='n'));
return a;
}
//My sad attempt to test if number given is a letter
int is_number(int num){
do{
printf("\n:");
scanf("%d",&num);
if( isalpha(num)){
printf("\nYou entered a letter, please input a number\n");
continue;
}
else{
printf("Number accepted...\n");
break;
}
}while(isalpha(num));
return num;
}
int main(){
char YesNo1;
int start;
int StartWait=500;
//char Choice;
int number1;
int number2;
int number3;
int number4;
printf("Welcome to simple calculator 0.01\n");
printf("At this stage calculator supports only 4 numbers\n");
printf("Would you like to start simple calculator?\n");
printf("Y/N?\n");
//Calls for check_yesno_question
YesNo1=check_yesno_question(YesNo1);
//Checks if answer is yes proceed, if answer is no, return 0;
if((YesNo1=='y')||(YesNo1=='Y')){
printf("Awnser = Yes\n");
printf("Starting up the calculator");
for(start=0;start<3;start++){
printf(".");
Sleep(StartWait);
}
printf("\n");
}
else{
printf("Awnser = No\n");
printf("Turning of the calculator");
for(start=0;start<3;start++){
printf(".");
Sleep(StartWait);
}
printf("\n");
return 0;
}
//Me wanting to make things look bit more clean
system("cls");
printf("---------------CALCULATOR---------------\n");
//Calls for is_number
number1=is_number(number1);
return 0;
}
As you seen it is unfinished. I'm basically done looking for answers myself. When this was posted my time was 4:04am