c++异常处理

7-1 数字格式异常 (10 分)
 

(NumberFormatException数字格式异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次输入数字。

输入格式:

i 9 (第1次输入) l 8 (第2次输入) 5 6 (第3次输入)

输出格式:

Incorrect input and re-enter two integers: (第1次输出提示) Incorrect input and re-enter two integers: (第2次输出提示) Sum is 11 (输出结果)

输入样例:

i 9
l 8
5 6

输出样例:

Incorrect input and re-enter two integers:
Incorrect input and re-enter two integers:
Sum is 11

#include <iostream>
#include<string.h>
using namespace std;
int f;
int toNumb(char co[])
{
    int len=strlen(co);
    int i;
    int sum=0;
    int w=1;
    for(i=len-1;i>=0;i--)
    {
        if(!(co[i]<='9' && co[i]>='0'))
        {
            f=1;
            return 0;
        }
        sum+=w*(co[i]-'0');
        w*=10;
    }
    return sum;
}
int main ()
{
    string a,b;
    while(1)
    {
        cin>>a>>b;
        f=0;
        int m=toNumb(&a[0]);
        int n=toNumb(&b[0]);
        if(f)
        {
            cout<<"Incorrect input and re-enter two integers:"<<endl;
            continue;
        }
        else
        {
            cout<<"Sum is "<<m+n<<endl;
            break;
        }
    }

} 
不一样的烟火
原文地址:https://www.cnblogs.com/cstdio1/p/10975686.html