由于我在谈论编码时非常环保,因此我一直在尝试制作一个小型计算器程序来测试自己的技能。无论如何,我都试图用一个循环来生成一个函数,该循环将要求输入数字,直到输入数字并拒绝字母为止。
这是我有限的理解/追寻所产生的:
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;
}
唯一的问题是,如果收到一封信,它会崩溃,但是有进步……同一封邮件没有不定式的垃圾邮件。
下一个代码是整个代码,而不只是片段:
#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;
}
如您所见,它尚未完成。 我基本上已经完成寻找自己的答案。发布时,我的时间是凌晨4:04
答案 0 :(得分:2)
从上下文来看,很明显您对它是否是字母不感兴趣。您只想知道它是否是数字。如果不是数字,则不必担心它是字母,特殊字符还是其他东西。
假设以上情况,您使用的方法错误,并且您使用的scanf
也不正确。只要读取成功,scanf("%d", &num)
就会始终将数字读入num
。您需要做的是检查阅读是否成功。
do{
printf("\n:");
if(scanf("%d",&num) != 1) { // If we did not perform a successful read
printf("\nRead failed. Please input a number\n");
continue;
} else {
...