检查输入类型而不退出程序并重新启动它

我需要获得两个整数并添加并打印添加的值。 我写了一个工作程序。 另一个要求是检查输入值是否不是整数,如果它不是整数,如果不关闭程序,它应该再次询问输入。

C代码

#include  void main() { int a,b,c; printf("This is a Addition program"); printf("\n Enter value of a:"); scanf("%d",&a); printf("\n Enter value of b:"); scanf("%d",&b); c=a+b; printf("\n The added value is %d",c); } 

这里有一些代码可以完全满足您的要求。 昨天David C Rankin在Stack Overflow中发布了相同基本问题的答案 。

这段代码基本上是David提供的:

 #include  static int getInt(const char *prompt) { int value; char c; while(printf("%s",prompt) && scanf("%d", &value) !=1) { do { c = getchar(); } while ( c != '\n' && c != EOF ); // flush input printf ("Invalid Entry, Try Again...\n"); } return value; } int sum(int a , int b) { return ( a + b ); } int main(){ int a , b; a = getInt("Please enter a number"); b = getInt("Please enter a number"); printf("Sum is :%d" , sum(a,b)); } 

函数getInt检查输入并为错误的输入大喊。

这个程序会做你想要的

 #include int main() //use int not void { int a,b,c; printf("This is a Addition program"); printf("\n Enter value of a:"); while(scanf("%d",&a)==0) { printf("\n Invalid input.Try again:"); getchar(); // clear the previous input } printf("\n Enter value of b:"); while(scanf("%d",&b)==0) { printf("\n Invalid input.Try again:"); getchar(); // clear the previous input } c=a+b; printf("\n The added value is %d",c); return 0; // because main returns int } 

scanf返回成功读取的项目数,因此如果输入了有效值,它将在您的情况下返回1。 如果不是,则输入无效的整数值, scanf将返回0。

使用fgets()/sscanf()/strto...()而不是scanf()

scanf()在同一个函数中解析并执行输入,并且不能很好地处理意外输入。 使用fgets()进行用户输入, 然后扫描/解析。

 #include  #include  #include  #include  int getint(const char *prompt) { char buf[sizeof(int) * CHAR_BIT]; while (1) { fputs(prompt, stdout); fflush(stdout); if (fgets(buf, sizeof buf, stdin) == NULL) { // sample handling of unexpected input issue. // Value to return of EOF or IO error return INT_MIN; } /// strtol() is another option int i, n; // " %n" notes offset of non-white-space after the numebr. if (1 == sscanf(buf, "%d %n", &i, &n) && buf[n] == '\0') { return i; } } } int main(void) { int a, b, c; printf("This is a Addition program"); a = getint("\n Enter value of a:"); b = getint("\n Enter value of b:"); c = a + b; printf("\n The added value is %d", c); return 0; }