检查输入类型不退出程序,并重新启动它 [英] Checking input type without quitting the program and restarting it

查看:139
本文介绍了检查输入类型不退出程序,并重新启动它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求得到两个整数,并添加和打印附加值。我写了一个工作计划。另一个要求是检查输入值是否大于其他整数,如果它比其他的整数,不关闭程序,应要求再次输入。

C $ C $ç

 的#include<&stdio.h中GT;无效的主要()
{
    诠释A,B,C;    的printf(这是一个加法程序);    的printf(\\ n输入的值:);
    scanf函数(%d个,&安培; A);
    的printf(\\ n输入的B值:);
    scanf函数(%D,和b);    C = A + B;    的printf(\\ n业增加值为%d,C);
}


解决方案

下面是一些code,将完全履行您的要求。昨天大卫ç兰张贴了的回答以基本相同的<一个href=\"http://stackoverflow.com/questions/26315822/scanf-validation-sits-and-waits-for-another-input-why\">question在堆栈溢出。

这code基本上是大卫提供的:

 的#include&LT;&stdio.h中GT;静态INT调用getInt(为const char *提示)
{
    int值;
    焦炭℃;    而(的printf(%S,提示)及和放大器; scanf函数(%d个,&安培;!值)= 1)
    {
     做{C =的getchar(); }而(C ='\\ n'和;!和C = EOF!); //刷新输入
            的printf(无效的输入,再试一次... \\ n);
    }    返回值;
}INT总和(INT A,INT B){回报(A + B); }诠释主(){    诠释A,B;    A =调用getInt(请输入一个数字);
    B =调用getInt(请输入一个数字);    的printf(总和是:%D,SUM(A,B));}

函数的调用getInt 检查输入和叫喊了错误输入。

I have a requirement to get two integers and add and print the added value. I wrote a working program. Another requirement is to check whether the input value is other than integer and if it is other than integer, without closing the program, it should again ask for the inputs.

C Code

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

解决方案

Here's some code that will completely fulfil your requirement. Yesterday David C Rankin posted an answer to the same basic question in Stack Overflow.

This code is basically what David provided:

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

}

The function getInt check the input and yells for the wrong input.

这篇关于检查输入类型不退出程序,并重新启动它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆