我已经做了大量的编程和arduino,并且想学习C语言,因为这也是我目前的学习要求。目前,我正在尝试制作一个程序来检查“ age”变量是否包含字符。这将为用户提供一条错误消息,该错误消息将一直循环直到输入为数字。这是我目前所拥有的:
#include <stdio.h>
#include <ctype.h>
#define MAXIMUM 10
#define BASE 10
char name[MAXIMUM]; // Input[Range to prevent overflow]
int age = 0; // Input
int nage; // nage = age + 1;
int error1 = 0;
void errorProgram()
{
if (isdigit(age))
{
error1 = 0;
printf("Error = 0\n");
}
else {
error1 = 1;
printf("Error = 1\n");
}
}
void main(void)
{
system("cls");
printf("What is your name: ");
scanf("%15[^\n]", name);
system("cls");
printf("What is your age: ");
scanf("%d", &age);
errorProgram();
while (error1 != 0) {
printf("Age contains character, please enter again: ");
scanf("%d", &age);
}
nage = age + 1;
system("cls");
printf("Hello %s, you'll be %d next year.", name, nage);
return(0);
}
这就是当我只是忽略您的名字部分而运行程序时发生的情况
场景1(数字)
输出
What is your age:
输入
5
输出
Error = 1
Age contains character, please enter again:
按下Enter键后,它将使用while循环再次询问它,直到我正确为止,这是希望的行为。但是,似乎可以将年龄视为角色?
方案2(字符)
输出
What is your age:
输入
d
输出
Age contains character, please enter again: d
Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character,
我想知道为什么如果我输入一个字符,它会在控制台上向各行发送垃圾邮件。 5和d都抛出error1 = 1,但while函数似乎在处理字符时表现出不同的行为。
有人可以解释这种行为吗?
顺便说一句,我正在使用研究中的模板,该模板使用“无效主体”。因此有点不同。
答案 0 :(得分:0)
以下建议的代码:
stdin
并重试获取age
#defines
,变量和无用的代码scanf()
输入name
字符串printf()
而不是等待程序结束(其中操作系统将从printf()
输出最终的数据system( "cls" );
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXIMUM 100
char name[MAXIMUM]; // Input[Range to prevent overflow]
int age = 0; // Input
int main(void)
{
//system("cls");
printf("\nWhat is your name: ");
if( scanf("%99[^\n]", name) != 1 )
{
fprintf( stderr, "scanf for name failed\n" );
exit( EXIT_FAILURE );
}
//system("cls");
printf("\nWhat is your age: ");
if( scanf("%d", &age) != 1 )
{
fprintf( stderr, "scanf for age failed\n" );
exit( EXIT_FAILURE );
}
//system("cls");
printf("\nHello %s, you'll be %d next year.\n", name, age+1);
return(0);
}