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

时间:2014-10-12 06:47:11

标签: c

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

C代码

#include <stdio.h>

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);
}

3 个答案:

答案 0 :(得分:1)

这里有一些完全符合您要求的代码。昨天David C Rankin向Stack Overflow中的相同基本answer发布了question

此代码基本上是David提供的内容:

#include <stdio.h>

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 检查输入并为错误的输入大喊。

答案 1 :(得分:0)

这个程序可以做你想要的事情

#include<stdio.h>
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.

答案 2 :(得分:0)

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

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

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdio.h>

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;
}